<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Jobs\Order\OrderDeliverInfoManage;
use App\Jobs\Shop\ShopOrderDeliverInfoManage;
use App\Models\Bureau\WxBureau;
use App\Models\Bureau\WxBureauGroup;
use App\Models\Bureau\WxClubTeam;
use App\Models\Posts\WxPost;
use App\Models\Circle\WxCircle;
use App\Models\Posts\WxPostsPayContent;
use App\Models\Posts\WxPostsWeightRefresh;
use App\Models\Shop\WxShopAddress;
use App\Models\Shop\WxShopCart;
use App\Models\Shop\WxShopContact;
use App\Models\Shop\WxShopGoods;
use App\Models\Shop\WxShopGoodsProduct;
use App\Models\Shop\WxShopOrder;
use App\Models\Shop\WxShopOrderGoods;
use App\Models\Used\WxUsedGood;
use App\Models\User\WxUserContactApply;
use App\Models\User\WxUserPay;
use App\Models\User\WxUserSetting;
use App\Models\WxDomainAuth;
use App\Wen\Utils\OrderUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\ShopUtils;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Http\Controllers\Api\Traits\PayTrait;
use App\Models\WxOrder;
use App\Models\User\WxUser;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class OrderController extends BaseController
{
    use PayTrait;

    public function coin_pay(Request $request){
        DB::beginTransaction();
        try {
            // todo:
            $uid = $request->uid;
            $order = $request->order;

            if(_array_key($order, 'type', 0) == 1){
                // 商品兑换
                if(_empty_(_array_key($order, 'cart_id', 0))){
                    DB::rollBack();
                    return $this->fail(200001);
                }
                $aid = $order['aid'];
                $cart_id = $order['cart_id'];
                $user_remark = $order['user_remark'];


                $CartItem = WxShopCart::find($cart_id);
                if(_empty_($CartItem)){
                    DB::rollBack();
                    return $this->fail(200004, [], '数据被清除，请重新下单再试');
                }
                $product_id = $CartItem->product_id;
                $WxShopGoodsProduct = WxShopGoodsProduct::find($product_id);
                if(_empty_($WxShopGoodsProduct)){
                    DB::rollBack();
                    return $this->fail(200004, [], '规格数据被清除，请重新下单再试');
                }

                $num = $CartItem->num;
                $goods_id = $CartItem->goods_id;
                $WxShopGoods = WxShopGoods::find($goods_id);
                if(_empty_($WxShopGoods)){
                    DB::rollBack();
                    return $this->fail(200004, [], '商品不存在，请重新下单再试');
                }

                if($WxShopGoodsProduct->credit_type === 0){
                    $price = (int)$WxShopGoodsProduct->price;
                    $vip_price = (int)$WxShopGoodsProduct->vip_price;

                    $price_total = $price * $num;
                    $vip_price_total = $vip_price * $num;

                    $buy_user = WxUser::where('id', $uid)->first();
                    $is_vip = $buy_user->is_member;

                    $order_total = $is_vip ? $vip_price_total : $price_total;

                    $has_coins = get_user_meta($uid, 'coins', 'n');
                    if(_empty_($has_coins)){
                        $has_coins = 0;
                    }
                    if($has_coins < _abs($order_total)){
                        DB::rollBack();
                        return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                    }
                    // todo:
                    $res = UserUtils::update_user_coins($uid, 23, -$order_total, '兑换了商品（id：'.$goods_id.' 规格：'.$WxShopGoodsProduct->param_value.' * '.$num.'），'.Settings::get('app_coin_name', '硬币') .'-'.$order_total );
                    if($res) {
                        $NotifyController = new NotifyController();
                        $orderSn = Utils::getSn(1);//生成订单号

                        if($WxShopGoods->type == 5){
                            $addsinfo = [
                                'id' => 0,
                                'name' => '',
                                'mobile' => '',
                                'province' => '',
                                'city' => '',
                                'county' => '',
                                'adds' => '',
                            ];
                        }else{
                            $addsinfo = WxShopAddress::where('user_id', $uid)->where('id', $aid)->first();//获取配送地址
                            if (!$addsinfo) {
                                DB::rollBack();
                                return $this->fail(800003);
                            }
                        }


                        //生成SHOP订单
                        $model = new WxShopOrder();
                        $model->user_id = $uid;
                        $model->order_id = $orderSn;//订单号

                        $model->goods_amount = 0;//商品总价
                        $model->discounts_amount = 0;//优惠金额
                        $model->order_amount = 0;//订单总额

                        $model->goods_amount_coin = $price_total;//商品总价
                        $model->discounts_amount_coin = $is_vip ? ($price_total - $vip_price_total) : 0;//优惠金额
                        $model->order_amount_coin = $order_total;//订单总额

                        $model->adds_id = $addsinfo['id'];//收货地址id
                        $model->adds_name = $addsinfo['name'];//收货人姓名
                        $model->adds_mobile = $addsinfo['mobile'];//收货人电话
                        $model->address = $addsinfo['province'] . $addsinfo['city'] . $addsinfo['county'] . $addsinfo['adds'];//收货详细地址
                        $model->contact_id = $WxShopGoods->contact_id ?: 0;
                        $model->user_remark = $user_remark;//用户备注
                        $model->pay_status = 1;//支付状态 1=未付款 2=已付款 3=已退款
                        $model->status = 0;//发货状态 0=正常 1=未发货 2=已发货 3=确认收货 4=已退货 5=取消
                        $model->order_goods_id = [ $WxShopGoodsProduct->id ];
                        $model->save();

                        $orderId = $model->id;//获取订单id


                        //

                        //批量添加订单商品
                        $orderGoods = [];

                        $the_product = $WxShopGoodsProduct;
                        // 规格存在并且有存量时
                        if ($the_product) {
                            $k = 0;
                            $WxShopGoods = WxShopGoods::where('id', $the_product->goods_id)->first();
                            $good_servers = $WxShopGoods->service_id;
                            if (_empty_($good_servers)) {
                                $good_servers = '[]';
                            }
                            $created_at = date('Y-m-d H:i:s', time());
                            $good_servers = json_decode($good_servers, true);
                            $refund_deadline = Carbon::now()->addDays(7);
                            if (in_array(1, $good_servers)) {
                                $refund_deadline = Carbon::now();
                                $created_at = $refund_deadline;
                            }

                            $recharge = $is_vip ? $the_product->vip_price * $num : $the_product->price * $num;

                            $orderGoods[$k]['pic'] = $the_product->pic;
                            $orderGoods[$k]['name'] = $WxShopGoods->name;
                            $orderGoods[$k]['product'] = $the_product->param_value;
                            $orderGoods[$k]['vip_price'] = $the_product->vip_price;
                            $orderGoods[$k]['price'] = $the_product->price;
                            $orderGoods[$k]['credit_type'] = $the_product->credit_type;
                            $orderGoods[$k]['recharge'] = $recharge;
                            $orderGoods[$k]['quantity'] = $num;
                            $orderGoods[$k]['order_id'] = $orderId;
                            $orderGoods[$k]['seller_user_id'] = $WxShopGoods->user_id ?: 0;
                            $orderGoods[$k]['buyer_user_id'] = $uid;
                            $orderGoods[$k]['goods_id'] = $the_product->goods_id;
                            $orderGoods[$k]['goods_type'] = $WxShopGoods->type;
                            $orderGoods[$k]['product_id'] = $the_product->id;
                            $orderGoods[$k]['created_at'] = $created_at;
                            $orderGoods[$k]['refund_deadline'] = $refund_deadline;
                        }
                        $ogModel = new WxShopOrderGoods();
                        $ogModel->addAll($orderGoods);

                        //修改购物车数据
                        if (_array_key($order, 'cart_id', 0) > 0) {
                            WxShopCart::where('id', $order['cart_id'])->update(['state' => 2]);
                        }

                        WxShopOrder::where('id', $orderId)
                            ->update(['pay_status' => 2, 'status' => 1, 'coins_num' => 0, 'coins_pay' => 0, 'pay_way' => ShopUtils::generate_payway_text(0, $price_total - $vip_price_total, 0, 0, 0, $order_total)]);

                        // 理论上闲置商品不可以金币购买
                        $NotifyController->usedGoodPaied($orderId);
                        $NotifyController->bureauGoodPaied($orderId);


                        ShopUtils::paied_content_process($orderId);
                        // 理论上不需要
                        ShopUtils::split_shop_order_by_seller($orderId);
                        ShopUtils::split_shop_order_by_type($orderId);
                        ShopUtils::order_buys_and_stock($orderId);
                    }
                }else{
                    return $this->fail(200004, [], '该商品不是兑换商品');
                }
            }else if(_array_key($order, 'type', 0) == 6){

            }


            DB::commit();
            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200006, [], $e->getMessage());
        }
    }

    public function balance_pay(Request $request){
        DB::beginTransaction();
        try {
            $uid = $request->uid;
            $order = $request->order;
            $paycode = $request->paycode;

            global $__MINI_GLOBAL_PAYCODE_0__,$__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_PAYCODE_0__){
                if(_empty_($paycode)){
                    return $this->fail(200004, [], '请先输入支付密码');
                }
                if(is_array($paycode) && str_replace(',', '', implode(',', $paycode)) !== get_user_meta($uid, 'paycode', 's')){
                    return $this->fail(200043, [
                        'title' => '支付密码错误',
                        'content' => '已忘记，前往修改？',
                        'confirmText' => '去修改',
                        'target_type' => 6,
                        'target_id' => '/pagesA/mine/paycode/forget'
                    ], '支付密码错误');
                }
                if(is_string($paycode) && $paycode !== get_user_meta($uid, 'paycode', 's')){
                    return $this->fail(200004, [], '支付密码不匹配');
                }
            }

            $user_coins = UserUtils::user_coins($uid);
            global $__MINI_GLOBAL_PAYCODE_17__;
            if(!$__MINI_GLOBAL_PAYCODE_17__){
                $order['coins_num'] = 0;
            }
            if( _array_key($order, 'coins_num', 0) <= 0){
                $order['coins_num'] = 0;
            }else if($user_coins < $order['coins_num']){
                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
            }
            $buy_user = WxUser::where('id', $uid)->first();
            $is_vip = $buy_user->is_member;

            $balance = UserUtils::user_balance($uid);
            $orderSn = Utils::getSn(1);
            $coin_rate = Settings::get('app_coin_pay_rate', 100);
            $coin_blance = round($order['coins_num'] / $coin_rate, 2);
            if($coin_blance < 0.01){
                $coin_blance = 0;
                $order['coins_num'] = 0;
            }

            // 开会员
            if (_array_key($order, 'type', 0) == 1) {
                // 修改使用金币的数量
                if($order['price'] <= $coin_blance){
                    $coin_blance = $order['price'];
                    $order['coins_num'] = (int)($coin_blance * $coin_rate);
                }

                if($order['coins_num'] > 0){
                    $coin_pay_percent_every = _between_(Settings::get('app_coin_pay_percent_every', 30), 0, 100);
                    if($coin_pay_percent_every > 0){
                        if( ($order['price'] * $coin_pay_percent_every / 100) < $coin_blance ){
                            DB::rollBack();
                            return $this->fail(200004, [], Settings::get('app_coin_name', '硬币').'抵扣不能超过'.$coin_pay_percent_every.'%');
                        }
                    }
                }


                if(_empty_(_array_key($order, 'price', 0)) || _empty_(_array_key($order, 'days', 0))){
                    return $this->fail(200004);
                }
                if($balance - $order['price'] + $coin_blance < 0){
                    return $this->fail(200012);
                }

                $vip_options = json_decode(Settings::get('app_vip_options', '[]'), true);
                if(_empty_($vip_options)){
                    return $this->fail(200004, [], '管理员暂未配置会员套餐');
                }
                $flag = false;
                $coins = 0;
                foreach ($vip_options as $option){
                    if($option && $option['days'] == $order['days'] && $option['price'] == $order['price']){
                        $flag = true;
                        $coins = $option['coins'];
                        break;
                    }
                }
                if($flag){
                    $orderModel = $this->createOrder($uid,1,'开通会员',$order['price'],$order['price'],$orderSn);
                    if($order['coins_num'] > 0){
                        $need_pay_price = $order['price'] - $coin_blance;
                        if($need_pay_price < 0.01){
                            // 金币直接结清
                            $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], '开通'.$order['days'].'天会员（'. $order['coins_num']. Settings::get('app_coin_name', '硬币') . '抵扣了￥'.$coin_blance.'）：金币-'.$order['coins_num']);
                            if($pay_res2){
                                WxUserRepositores::vip($uid, $order['days']);
                                if($coins > 0){
                                    UserUtils::update_user_coins($uid, 13, $coins, '开通'.$order['days'].'天会员，赠送'.$coins.Settings::get('app_coin_name', '硬币'));
                                }
                                // 上级奖励

                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            $pay_res = UserUtils::update_user_financial($uid, 11, $need_pay_price, '您花费了￥'.$need_pay_price.'余额+'.$order['coins_num'].Settings::get('app_coin_name', '硬币').'开通了'.$order['days'].'天会员');
                            if($pay_res){
                                $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], '开通'.$order['days'].'天会员（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'. Settings::get('app_coin_name', '硬币') .'-'.$order['coins_num']);
                                if($pay_res2){
                                    WxUserRepositores::vip($uid, $order['days']);
                                    if($coins > 0){
                                        UserUtils::update_user_coins($uid,13, $coins, '开通'.$order['days'].'天会员，赠送'.$coins.Settings::get('app_coin_name', '硬币'));
                                    }
                                }else{
                                    DB::rollBack();
                                    return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                                }
                            }else{
                                DB::rollBack();
                                return $this->fail(200012);
                            }
                        }
                    }else{
                        $pay_res = UserUtils::update_user_financial($uid, 11, $order['price'], '您花费了￥'.$order['price'].'余额开通了'.$order['days'].'天会员');
                        if($pay_res){
                            WxUserRepositores::vip($uid, $order['days']);
                            if($coins > 0){
                                UserUtils::update_user_coins($uid,13,  $coins, '开通'.$order['days'].'天会员，赠送'.$coins.Settings::get('app_coin_name', '硬币'));
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200012);
                        }
                    }
                }else{
                    return $this->fail(200004, [], '管理员暂未配置￥'.$option['price'].'的'.$order['days'].'天套餐');
                }
                WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                // 创建订单
                DB::commit();
                return $this->success(['tip'=>'恭喜，会员天数增加'.$order['days'].'天']);
            }
            // 充电
            else if (_array_key($order, 'type', 0) == 2) {
                if(_array_key($order, 'rewardPrice', 0) <= 0){
                    return $this->fail(200004);
                }

                $order['postsId'] = _abs($order['postsId']);

                // 修改使用金币的数量
                if($order['rewardPrice'] <= $coin_blance){
                    $coin_blance = $order['rewardPrice'];
                    $order['coins_num'] = (int)($coin_blance * $coin_rate);
                }

                if($order['coins_num'] > 0){
                    $coin_pay_percent_every = _between_(Settings::get('app_coin_pay_percent_every', 30), 0, 100);
                    if($coin_pay_percent_every > 0){
                        if( ($order['rewardPrice'] * $coin_pay_percent_every / 100) < $coin_blance ){
                            DB::rollBack();
                            return $this->fail(200004, [], Settings::get('app_coin_name', '硬币').'抵扣不能超过'.$coin_pay_percent_every.'%');
                        }
                    }
                }


                if($balance - $order['rewardPrice'] + $coin_blance < 0){
                    return $this->fail(200012);
                }
                $parame = serialize($order);
                // 创建订单
                $orderModel = $this->createOrder($uid,2,'充电',$order['rewardPrice'],$order['rewardPrice'],$orderSn,$parame);
                if($order['coins_num'] > 0){
                    // 仅金币支付
                    $need_pay_price = $order['rewardPrice'] - $coin_blance;
                    if($need_pay_price < 0.01){
                        $pay_res2 = UserUtils::update_user_coins($uid,3, -$order['coins_num'], '充电了内容(id: '.$order['postsId'].')￥'.$order['rewardPrice'].'（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：金币-'.$order['coins_num']);
                        if($pay_res2){
                            // 创建订单
                            OrderUtils::exceptional($orderModel);
                        }else{
                            DB::rollBack();
                            return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                        }
                    }else{
                        // 金币+余额支付
                        $pay_res = UserUtils::update_user_financial($uid, 10, $need_pay_price, '您通过余额付费(消耗'.$order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了'.$coin_blance.')充电了「<a href="/pages/sticky/sticky?id='.$order['postsId'].'">笔记（id：'.$order['postsId'].'）</a>」，充电金额￥'.$order['rewardPrice'], $order['postsId']);
                        // 处理通知
                        if($pay_res){
                            $pay_res2 = UserUtils::update_user_coins($uid,3, -$order['coins_num'], '充电了内容(id: '.$order['postsId'].')￥'.$order['rewardPrice'].'（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'.Settings::get('app_coin_name', '硬币').'-'.$order['coins_num']);
                            if($pay_res2){
                                // 创建订单
                                OrderUtils::exceptional($orderModel);
                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200012);
                        }
                    }
                }else{
                    // 余额支付
                    $pay_res = UserUtils::update_user_financial($uid, 10, $order['rewardPrice'], '您通过余额付费充电了「<a href="/pages/sticky/sticky?id='.$order['postsId'].'">笔记（id：'.$order['postsId'].'）</a>」，充电金额￥'.$order['rewardPrice'], $order['postsId']);
                    // 处理通知
                    if($pay_res){
                        OrderUtils::exceptional($orderModel);
                    }else{
                        DB::rollBack();
                        return $this->fail(200012);
                    }
                }
                WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                DB::commit();
                return $this->success(['tip'=>'充电成功！']);
            }
            else if (_array_key($order, 'type', 0) == 4) {
                // 购买付费
                if(_empty_(_array_key($order, 'post_id', 0)) || _empty_(_array_key($order, 'scene', 0))){
                    return $this->fail(200004);
                }
                $res = $this->processPayPost($uid, $order['post_id'], $order['scene'], $orderSn, $order['coins_num'], $coin_blance, $coin_rate);
                if($res['code'] == 1){
                    DB::commit();
                    return $this->success($res['data']);
                }else{
                    DB::rollBack();
                    return $this->fail($res['code'], [], $res['tip']);
                }
            }
            else if (_array_key($order, 'type', 0) == 5) {

                if(!isset($order['goods_amount']) || !isset($order['discounts_amount']) || !isset($order['order_amount']) || !isset($order['order_goods'])){
                    return $this->fail(200004);
                }

                $goods_amount = $order['goods_amount'];
                $discounts_amount = $order['discounts_amount'];
                $order_amount = $order['order_amount'];
                $order_goods = $order['order_goods'];
                $user_remark = $order['user_remark'];
                $aid = $order['aid'];
                $seller_user_id = null;
                // 0:电商 6：二手
                $order_from = 0;
                $contact_id = 0;
                $order_goods_id = [];

                $notify_controller = new NotifyController();

                $acculate_amount = 0;
                $acculate_vip_amount = 0;
                foreach ($order_goods as $order_good){
                    if($order_good['goods_type'] == 6){
                        // 闲置
                        $the_used_good = WxUsedGood::where('id', $order_good['goods_id'])->where('status', 1)->first();
                        if($the_used_good){

                            $order_from = 6;
                            $seller_user_id = $the_used_good->user_id;
                            $order_goods_id[] = $the_used_good->id;

                            if($the_used_good->price != $order_good['price']){
                                DB::rollBack();
                                return $this->fail(200004, [], '参数1检验失败，疑似参数被纂改');
                            }else{
                                $acculate_amount += ($the_used_good->price * 1);
                                $acculate_vip_amount += ($the_used_good->price * 1);
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200003, [], '订单中存在已售出的闲置商品');
                        }

                    }else if($order_good['goods_type'] == 7){
                        $the_bureau_good = WxBureau::where('id', $order_good['goods_id'])->where('status', 1)->first();
                        $the_club_team = WxClubTeam::find($order_good['product_id']);
                        if(!_empty_($the_bureau_good) && !_empty_($the_club_team)){
                            $the_bureau_group = WxBureauGroup::find($the_club_team->group_id);
                            if(_empty_($the_bureau_group)){
                                DB::rollBack();
                                return $this->fail(200003, [], '订单中指定的组局分组不存在');
                            }
                            $order_from = 7;
                            $seller_user_id = $the_bureau_good->user_id;
                            $order_goods_id[] = $the_bureau_good->id;

                            if($the_bureau_good->type == 2){
                                DB::rollBack();
                                return $this->fail(200003, [], '暂不能处理战队比赛');
                            }

                            // 有没有席位
                            $members_arr = $the_club_team->members;
                            if(count($members_arr) >= $the_club_team->members_limit){
                                DB::rollBack();
                                // todo: 这里有点粗糙，还需要检查支付中的订单
                                return $this->fail(200004, [], '已满员');
                            }

                            // 检验性别
                            if($the_bureau_group->signup_gender > 0){
                                if($the_bureau_group->signup_gender == 1){
                                    if($buy_user->gender != 1){
                                        DB::rollBack();
                                        return $this->fail(200004, [], '仅限男性参加');
                                    }
                                }else if($the_bureau_group->signup_gender == 2){
                                    if($buy_user->gender != 2){
                                        DB::rollBack();
                                        return $this->fail(200004, [], '仅限女性参加');
                                    }
                                }
                            }

                            if($the_bureau_group->is_real_name == 1){
                                if(_empty_($buy_user->real_name)){
                                    DB::rollBack();
                                    return $this->fail(200043, [
                                        'title' => '未实名认证',
                                        'content' => '您还没有实名认证，是否前往认证',
                                        'confirmText' => '去认证',
                                        'target_type' => 6,
                                        'target_id' => '/pagesA/mine/realname/realname'
                                    ], '需实名认证');
                                }
                            }

                            if($the_bureau_group->cost_per_person != $order_good['price']){
                                DB::rollBack();
                                return $this->fail(200004, [], '参数1检验失败，疑似参数被纂改');
                            }else{
                                $acculate_amount += ($the_bureau_group->cost_per_person * 1);
                                $acculate_vip_amount += ($the_bureau_group->cost_per_person * 1);
                                $contact_id = WxShopContact::where('club_id', $the_bureau_good->club_id)->value('id');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200004, [], '订单中存在非正常状态的闲置组局');
                        }
                    }else{
                        $the_product = WxShopGoodsProduct::where([['id', '=', $order_good['product_id']],['goods_id','=', $order_good['goods_id']],['state', '=', 0]])->first();
                        if($the_product){
                            $order_goods_id[] = $the_product->goods_id;
                            if($order_good['goods_type'] == 5){
                                $WxShopGoods = WxShopGoods::where('id', $the_product->goods_id)->first();
                                $contact_id = $WxShopGoods->contact_id;
                            }
                            if($the_product->price != $order_good['price'] || $the_product->vip_price != $order_good['vip_price']){
                                DB::rollBack();
                                return $this->fail(200004, [], '参数1检验失败，疑似参数被纂改');
                            }else{
                                $product_seller = WxShopGoods::where('id', $the_product->goods_id)->value('user_id');
                                if(_empty_($seller_user_id)){
                                    $seller_user_id = $product_seller;
                                }else{
                                    if($seller_user_id == $product_seller){

                                    }else{
                                        $seller_user_id = null;
                                    }
                                }
                                $acculate_amount += ($the_product->price * $order_good['num']);
                                $acculate_vip_amount += ($the_product->vip_price * $order_good['num']);
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200003);
                        }
                    }
                }
                $acculate_order_amount = $is_vip ? $acculate_vip_amount : $acculate_amount;
                if(_abs($acculate_order_amount - $order_amount) >= 0.5 || _abs(($acculate_amount - $acculate_order_amount) - $discounts_amount) >= 0.5){
                    DB::rollBack();
                    return $this->fail(200004, [], '参数2检验失败，疑似参数被纂改');
                }

                // 纠正前端数据
                $acculate_amount = round($acculate_amount, 2);
                $acculate_vip_amount = round($acculate_vip_amount, 2);
                $goods_amount = $acculate_amount;
                $discounts_amount = $is_vip ? round($acculate_amount - $acculate_vip_amount, 2) : 0;
                $order_amount = $is_vip ? $acculate_vip_amount : $acculate_amount;


                // 纠正使用金币的数量
                if($order_amount <= $coin_blance){
                    $coin_blance = $order_amount;
                    $order['coins_num'] = (int)($coin_blance * $coin_rate);
                }

                if( $order['coins_num'] > 0 ){
                    $coin_pay_percent_every = _between_(Settings::get('app_coin_pay_percent_every', 30), 0, 100);
                    if($coin_pay_percent_every > 0){
                        if( ($order_amount * $coin_pay_percent_every / 100) < $coin_blance ){
                            DB::rollBack();
                            return $this->fail(200004, [], Settings::get('app_coin_name', '硬币').'抵扣不能超过'.$coin_pay_percent_every.'%');
                        }
                    }
                }


                if($balance - $order_amount + $coin_blance < 0){
                    return $this->fail(200012);
                }

                $orderSn = Utils::getSn(1);//生成订单号

                if($contact_id > 0 && _empty_($aid)){
                    $addsinfo = [
                        'id' => 0,
                        'name' => '',
                        'mobile' => '',
                        'province' => '',
                        'city' => '',
                        'county' => '',
                        'adds' => '',
                    ];
                }else{
                    $addsinfo = WxShopAddress::where('user_id', $uid)->where('id', $aid)->first();//获取配送地址
                    if(!$addsinfo){
                        DB::rollBack();
                        return $this->fail(800003);
                    }
                }


                //生成SHOP订单
                $order_model = new WxShopOrder();
                $order_model->user_id = $uid;
                $order_model->order_id = $orderSn;//订单号
                $order_model->goods_amount = $goods_amount;//商品总价
                $order_model->discounts_amount = $discounts_amount;//优惠金额
                $order_model->order_amount = $order_amount;//订单总额
                $order_model->adds_id = $addsinfo['id'];//收货地址id
                $order_model->adds_name = $addsinfo['name'];//收货人姓名
                $order_model->adds_mobile = $addsinfo['mobile'];//收货人电话
                $order_model->address = $addsinfo['province'] . $addsinfo['city'] . $addsinfo['county'] . $addsinfo['adds'];//收货详细地址
                $order_model->contact_id = $contact_id;
                $order_model->user_remark = $user_remark;//用户备注
                $order_model->pay_status = 1;//支付状态 1=未付款 2=已付款 3=已退款
                $order_model->status = 0;//发货状态 0=正常 1=未发货 2=已发货 3=确认收货 4=已退货 5=取消 6=用户删除 7=退款中
                $order_model->order_from = $order_from;
                $order_model->order_goods_id = $order_goods_id;
                if($seller_user_id > 0){
                    // 单个的商户则直接补充 seller_user_id， 多个商户由于不确定是哪个商户，直接为null，拆订单的时候再补充
                    $order_model->seller_user_id = $seller_user_id;
                }

                $order_model->save();

                $orderId = $order_model->id;//获取订单id


                //
                $_goods_amount = 0;
                $_order_amount = 0;

                //批量添加订单商品
                $orderGoods = [];
                foreach ($order_goods as $k => $v) {
                    if($v['goods_type'] == 6){
                        $the_used_good = WxUsedGood::where('id', $v['goods_id'])->where('status', 1)->first();
                        if ($the_used_good) {
                            if($the_used_good->image_urls){
                                $the_used_good->pic = _array_key($the_used_good->image_urls[0], 'url', '') . '';
                            }

                            $created_at = date('Y-m-d H:i:s', time());
                            $good_servers = [2];
                            $refund_deadline = Carbon::now()->addDays(7);
                            if(in_array(1, $good_servers)){
                                $refund_deadline = Carbon::now();
                                $created_at = $refund_deadline;
                            }

                            $recharge = $the_used_good->price * 1;
                            $_order_amount += $recharge;
                            $_goods_amount += $the_used_good->price * 1;

                            $orderGoods[$k]['pic'] = $the_used_good->pic;
                            $orderGoods[$k]['name'] = $the_used_good->title;
                            $orderGoods[$k]['product'] = '';
                            $orderGoods[$k]['vip_price'] = $the_used_good->price;
                            $orderGoods[$k]['price'] = $the_used_good->price;
                            $orderGoods[$k]['recharge'] = $recharge;
                            $orderGoods[$k]['quantity'] = 1;
                            $orderGoods[$k]['order_id'] = $orderId;
                            $orderGoods[$k]['seller_user_id'] = $the_used_good->user_id;
                            $orderGoods[$k]['buyer_user_id'] = $uid;
                            $orderGoods[$k]['goods_id'] = $the_used_good->id;
                            $orderGoods[$k]['goods_type'] = 6;
                            $orderGoods[$k]['product_id'] = 0;
                            $orderGoods[$k]['created_at'] = $created_at;
                            $orderGoods[$k]['refund_deadline'] = $refund_deadline;

                        }else{
                            DB::rollBack();
                            return $this->fail(200003);
                        }
                    }else if($v['goods_type'] == 7){
                        $the_bureau_good = WxBureau::where('id', $v['goods_id'])->where('status', 1)->first();
                        $the_club_team = WxClubTeam::find($v['product_id']);
                        $the_bureau_group = WxBureauGroup::find($the_club_team ? $the_club_team->group_id : 0);
                        if(!_empty_($the_bureau_good) && !_empty_($the_club_team) && !_empty_($the_bureau_group)) {

                            // 临时暂用
                            if($the_bureau_good->image_urls){
                                $the_bureau_good->pic = _array_key($the_bureau_good->image_urls[0], 'url', '') . '';
                            }

                            // 允许退款的时间
                            $created_at = date('Y-m-d H:i:s', time());
                            $endDateTime = Carbon::createFromFormat('Y-m-d H:i:s', "{$the_bureau_good->service_date_end} {$the_bureau_good->service_time_end}");
                            $refund_policy = $the_bureau_good->refund_policy;
                            if($refund_policy == 255){
                                $refund_deadline = Carbon::now();
                                $created_at = $refund_deadline;
                            }else{
                                $refund_deadline = $endDateTime;
                            }


                            $recharge = $the_bureau_group->cost_per_person * 1;
                            $_order_amount += $recharge;
                            $_goods_amount += $the_bureau_group->cost_per_person * 1;
                            $orderGoods[$k]['pic'] = $the_bureau_good->pic;
                            $orderGoods[$k]['name'] = $the_bureau_good->title;
                            $orderGoods[$k]['product'] = '';
                            $orderGoods[$k]['vip_price'] = $the_bureau_group->cost_per_person;
                            $orderGoods[$k]['price'] = $the_bureau_group->cost_per_person;
                            $orderGoods[$k]['recharge'] = $recharge;
                            $orderGoods[$k]['quantity'] = 1;
                            $orderGoods[$k]['order_id'] = $orderId;
                            $orderGoods[$k]['seller_user_id'] = $the_bureau_good->user_id;
                            $orderGoods[$k]['buyer_user_id'] = $uid;
                            $orderGoods[$k]['goods_id'] = $the_bureau_good->id;
                            $orderGoods[$k]['goods_type'] = 7;
                            $orderGoods[$k]['product_id'] = $the_club_team->id;
                            $orderGoods[$k]['created_at'] = $created_at;
                            $orderGoods[$k]['refund_deadline'] = $refund_deadline;

                        } else{
                            DB::rollBack();
                            return $this->fail(200003);
                        }
                    }else{
                        $the_product = WxShopGoodsProduct::where('id', $v['product_id'])->first();
                        // 规格存在并且有存量时
                        if ($the_product) {
                            $WxShopGoods = WxShopGoods::where('id', $the_product->goods_id)->first();
                            $good_servers = $WxShopGoods->service_id;
                            if(_empty_($good_servers)){
                                $good_servers = '[]';
                            }

                            $created_at = date('Y-m-d H:i:s', time());
                            $good_servers = json_decode($good_servers, true);
                            $refund_deadline = Carbon::now()->addDays(7);
                            if(in_array(1, $good_servers)){
                                $refund_deadline = Carbon::now();
                                $created_at = $refund_deadline;
                            }

                            $recharge = $is_vip ? $the_product->vip_price * $v['num'] : $the_product->price * $v['num'];
                            $_order_amount += $recharge;
                            $_goods_amount += $the_product->price * $v['num'];

                            $orderGoods[$k]['pic'] = $the_product->pic;
                            $orderGoods[$k]['name'] = $v['goods_name'];
                            $orderGoods[$k]['product'] = $the_product->param_value;
                            $orderGoods[$k]['vip_price'] = $the_product->vip_price;
                            $orderGoods[$k]['price'] = $the_product->price;
                            $orderGoods[$k]['recharge'] = $recharge;
                            $orderGoods[$k]['quantity'] = $v['num'];
                            $orderGoods[$k]['order_id'] = $orderId;
                            $orderGoods[$k]['seller_user_id'] = $WxShopGoods->user_id ?: 0;
                            $orderGoods[$k]['buyer_user_id'] = $uid;
                            $orderGoods[$k]['goods_id'] = $the_product->goods_id;
                            $orderGoods[$k]['goods_type'] = $WxShopGoods->type;
                            $orderGoods[$k]['product_id'] = $the_product->id;
                            $orderGoods[$k]['created_at'] = $created_at;
                            $orderGoods[$k]['refund_deadline'] = $refund_deadline;
                        }else{
                            DB::rollBack();
                            return $this->fail(200003);
                        }
                    }
                }
                $ogModel = new WxShopOrderGoods();
                $ogModel->addAll($orderGoods);

                //修改购物车数据
                if(_array_key($order, 'cart_id', 0) > 0){
                    WxShopCart::where('id', $order['cart_id'])->update(['state' => 2]);
                }else{
                    WxShopCart::where('user_id', $uid)->where('is_check', 1)->where('state', 0)
                        ->update(['state' => 2]);
                }

                if($order_amount < 0.01){
                    WxShopOrder::where('id', $orderId)
                        ->update(['pay_status' => 2, 'status' => 1, 'coins_num'=>$order['coins_num'], 'coins_pay'=>$coin_blance, 'pay_way'=>ShopUtils::generate_payway_text($discounts_amount,0, 0, 0, 0, $order['coins_num'])]);
                    $notify_controller->usedGoodPaied($orderId);
                    $notify_controller->bureauGoodPaied($orderId);
                    ShopUtils::paied_content_process($orderId);
                    ShopUtils::split_shop_order_by_seller($orderId);
                    ShopUtils::split_shop_order_by_type($orderId);
                    ShopUtils::order_buys_and_stock($orderId);
                    WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                    DB::commit();
                    return $this->success(['tip'=>'订单结算成功！']);
                }

                if($order['coins_num'] > 0){
                    // 仅金币支付
                    $need_pay_price = $order_amount - $coin_blance;
                    if($need_pay_price < 0.01){
                        $pay_res2 = UserUtils::update_user_coins($uid,3, -$order['coins_num'], '购物车订单结算(商品订单id: '.$orderId.')￥'.$order_amount.'（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'.Settings::get('app_coin_name', '硬币').'-'.$order['coins_num']);
                        if($pay_res2){
                            WxShopOrder::where('id', $orderId)
                                ->update(['pay_status' => 2, 'status' => 1, 'coins_num'=>$order['coins_num'], 'coins_pay'=>$coin_blance, 'pay_way'=>ShopUtils::generate_payway_text($discounts_amount,0, 0, 0, 0, $order['coins_num'])]);

                            $notify_controller->usedGoodPaied($orderId);
                            $notify_controller->bureauGoodPaied($orderId);

                            ShopUtils::paied_content_process($orderId);
                            ShopUtils::split_shop_order_by_seller($orderId);
                            ShopUtils::split_shop_order_by_type($orderId);
                            ShopUtils::order_buys_and_stock($orderId);
                        }else{
                            DB::rollBack();
                            return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                        }
                    }else{
                        // 金币+余额支付
                        $pay_res = UserUtils::update_user_financial($uid, 13, $need_pay_price, '您通过余额付费(消耗'.$order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了'.$coin_blance.')结算了「<a href="/pagesA/shop/order/order">商品订单（id：'.$orderId.'）</a>」，订单金额￥'.$order_amount);
                        // 处理通知
                        if($pay_res){
                            $pay_res2 = UserUtils::update_user_coins($uid,3, -$order['coins_num'], '结算了商品订单(id: '.$orderId.')￥'.$order_amount.'（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'.Settings::get('app_coin_name', '硬币').'-'.$order['coins_num']);
                            if($pay_res2){
                                // 创建订单
                                WxShopOrder::where('id', $orderId)
                                    ->update(['pay_status' => 2, 'status' => 1, 'coins_num'=>$order['coins_num'], 'coins_pay'=>$coin_blance, 'pay_way'=>ShopUtils::generate_payway_text($discounts_amount, 0,0, 0, $need_pay_price, $order['coins_num'])]);

                                $notify_controller->usedGoodPaied($orderId);
                                $notify_controller->bureauGoodPaied($orderId);

                                ShopUtils::paied_content_process($orderId);
                                ShopUtils::split_shop_order_by_seller($orderId);
                                ShopUtils::split_shop_order_by_type($orderId);
                                ShopUtils::order_buys_and_stock($orderId);
                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200012);
                        }
                    }
                }else{
                    // 余额支付
                    $pay_res = UserUtils::update_user_financial($uid, 13, $order_amount, '您通过余额付费结算了「<a href="/pagesA/shop/order/order">商品订单（id：'.$orderId.'）</a>」，订单金额￥'.$order_amount);
                    // 处理通知
                    if($pay_res){
                        WxShopOrder::where('id', $orderId)
                            ->update(['pay_status' => 2, 'status' => 1, 'pay_way'=>ShopUtils::generate_payway_text($discounts_amount,0, 0, 0, $order_amount, 0)]);

                        $notify_controller->usedGoodPaied($orderId);
                        $notify_controller->bureauGoodPaied($orderId);

                        ShopUtils::paied_content_process($orderId);
                        ShopUtils::split_shop_order_by_seller($orderId);
                        ShopUtils::split_shop_order_by_type($orderId);
                        ShopUtils::order_buys_and_stock($orderId);
                    }else{
                        DB::rollBack();
                        return $this->fail(200012);
                    }
                }
                WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);

                DB::commit();
                return $this->success(['tip'=>'订单结算成功！']);

            }
            else if (_array_key($order, 'type', 0) == 6) {
                // 付费推广
                $is_promotion_refresh = false;
                $time_list = [];
                if(_array_key($order, 'is_refresh', 0) == 1){
                    if( _empty_(_array_key($order, 'post_id', 0)) || _empty_(_array_key($order, 'time_list', [])) ){
                        return $this->fail(200004);
                    }
                    $is_promotion_refresh = true;
                }else{
                    if(_empty_(_array_key($order, 'post_id', 0)) || _empty_(_array_key($order, 'index', 0), true)){
                        return $this->fail(200004);
                    }
                }
                $post_id = _array_key($order, 'post_id', 0);
                $post_id = _abs($post_id);
                $the_post = WxPost::where('id', $post_id)->where([['is_examine' ,'=', 1], ['posts_state' , '=', 0]])->first();
                if(!$the_post){
                    DB::rollBack();
                    return $this->fail(200004, [], '笔记不存在或非正常推送状态');
                }

                if($is_promotion_refresh){
                    $time_list = _array_key($order, 'time_list', []);
                    if(!is_array($time_list)){
                        return $this->fail(200004);
                    }
                    $the_order_price = bcdiv(Settings::get('app_promoted_post_refresh_cost', 1.0, true) * count($time_list), 1, 2);
                    $order_info_des = '笔记推广自动刷新'.count($time_list).'次';
                }else{

                    $tmp_tenant_id = -1;
                    if($__MINI_GLOBAL_TENANT_ID__ != $the_post->tenant_id){
                        $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                        $__MINI_GLOBAL_TENANT_ID__ = $the_post->tenant_id;
                    }
                    $post_options = Settings::get('app_promoted_post_options', [], true);
                    if($tmp_tenant_id > 0){
                        $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
                    }



                    $index_option = _array_key($order, 'index', 0);
                    if(_empty_($post_options) || !isset($post_options[$index_option])){
                        DB::rollBack();
                        return $this->fail(200004, [], '后台未配置index为'.$index_option.'的付费推广套餐');
                    }
                    $the_option = $post_options[$index_option];
                    if($the_option['credit_type'] != 1){
                        DB::rollBack();
                        return $this->fail(200004, [], '该接口只能进行余额付费推广');
                    }
                    $the_order_price = $the_option['price'];
                    $order_info_des = '笔记付费置顶'.$the_option['hour'].'小时';
                }


                // 修改使用金币的数量
                if($the_order_price <= $coin_blance){
                    $coin_blance = $the_order_price;
                    $order['coins_num'] = (int)($coin_blance * $coin_rate);
                }

                if($order['coins_num'] > 0){
                    $coin_pay_percent_every = _between_(Settings::get('app_coin_pay_percent_every', 30), 0, 100);
                    if($coin_pay_percent_every > 0){
                        if( ($the_order_price * $coin_pay_percent_every / 100) < $coin_blance ){
                            DB::rollBack();
                            return $this->fail(200004, [], Settings::get('app_coin_name', '硬币').'抵扣不能超过'.$coin_pay_percent_every.'%');
                        }
                    }
                }

                if($balance - $the_order_price + $coin_blance < 0){
                    return $this->fail(200012);
                }


                $orderModel = $this->createOrder($uid,6,$order_info_des,$the_order_price,$the_order_price,$orderSn);
                if($order['coins_num'] > 0){
                    $need_pay_price = $the_order_price - $coin_blance;
                    if($need_pay_price < 0.01){
                        // 金币直接结清
                        if($is_promotion_refresh){
                            $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], '笔记(id: '.$post_id.')付费推广自动刷新'.count($time_list).'次（'. $order['coins_num']. Settings::get('app_coin_name', '硬币') . '抵扣了￥'.$coin_blance.'）：金币-'.$order['coins_num']);
                            if($pay_res2){

                                $insert_data = [];
                                sort($time_list);
                                foreach ($time_list as $timestap){
                                    $insert_data[] = [
                                        'user_id' => $uid,
                                        'post_id' => $post_id,
                                        'expect_time' => Carbon::createFromTimestamp((int)($timestap / 1000)),
                                        'refresh_time' => null,
                                        'balance_cost' => 0,
                                        'coin_cost' => (int)($order['coins_num'] / count($time_list)),
                                        'status' => 0
                                    ];
                                }
                                WxPostsWeightRefresh::insert($insert_data);

                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], '笔记(id: '.$post_id.')付费推广'.$the_option['tip'].'（'. $order['coins_num']. Settings::get('app_coin_name', '硬币') . '抵扣了￥'.$coin_blance.'）：金币-'.$order['coins_num']);
                            if($pay_res2){

                                $the_weight = $the_post->weight;
                                if($the_weight < time()){
                                    $the_weight = time();
                                }
                                $the_weight += $the_option['hour'] * 3600;

                                WxPost::withoutSyncingToSearch(function () use ($post_id, $the_weight) {
                                    WxPost::where('id', $post_id)->update(['weight'=>timetostr($the_weight)]);
                                });

                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }
                    }else{
                        if($is_promotion_refresh){
                            $pay_res = UserUtils::update_user_financial($uid, 21, $need_pay_price, '您花费了￥'.$need_pay_price.'余额+'.$order['coins_num'].Settings::get('app_coin_name', '硬币').'推广了笔记'.$post_id.'(自动刷新：'.count($time_list).'次)', $post_id);
                            if($pay_res){
                                $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], '笔记(id: '.$post_id.')付费推广自动刷新'.count($time_list).'次（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'. Settings::get('app_coin_name', '硬币') .'-'.$order['coins_num']);
                                if($pay_res2){
                                    $post_refresh_cost = floor(($need_pay_price / count($time_list)) * 100) / 100;
                                    $insert_data = [];
                                    sort($time_list);
                                    foreach ($time_list as $timestap){
                                        $insert_data[] = [
                                            'user_id' => $uid,
                                            'post_id' => $post_id,
                                            'expect_time' => Carbon::createFromTimestamp((int)($timestap / 1000)),
                                            'refresh_time' => null,
                                            'coin_cost' => (int)($order['coins_num'] / count($time_list)),
                                            'balance_cost' => $post_refresh_cost,
                                            'status' => 0
                                        ];
                                    }
                                    WxPostsWeightRefresh::insert($insert_data);

                                }else{
                                    DB::rollBack();
                                    return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                                }
                            }else{
                                DB::rollBack();
                                return $this->fail(200012);
                            }
                        }else{
                            $pay_res = UserUtils::update_user_financial($uid, 21, $need_pay_price, '您花费了￥'.$need_pay_price.'余额+'.$order['coins_num'].Settings::get('app_coin_name', '硬币').'推广了笔记'.$post_id.'(增加时长：'.$the_option['tip'].')');
                            if($pay_res){
                                $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], '笔记(id: '.$post_id.')付费推广'.$the_option['tip'].'（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'. Settings::get('app_coin_name', '硬币') .'-'.$order['coins_num']);
                                if($pay_res2){

                                    $the_weight = $the_post->weight;
                                    if($the_weight < time()){
                                        $the_weight = time();
                                    }
                                    $the_weight += $the_option['hour'] * 3600;

                                    WxPost::withoutSyncingToSearch(function () use ($post_id, $the_weight) {
                                        WxPost::where('id', $post_id)->update(['weight'=>timetostr($the_weight)]);
                                    });

                                }else{
                                    DB::rollBack();
                                    return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                                }
                            }else{
                                DB::rollBack();
                                return $this->fail(200012);
                            }
                        }
                    }
                }else{

                    if($is_promotion_refresh){
                        $pay_res = UserUtils::update_user_financial($uid, 21, $the_order_price, '您花费￥'.$the_order_price.'推广了笔记'.$post_id.'(自动刷新：'.count($time_list).'次)', $post_id);
                        if($pay_res){
                            $post_refresh_cost = floor(($the_order_price / count($time_list)) * 100) / 100;
                            $insert_data = [];
                            sort($time_list);
                            foreach ($time_list as $timestap){
                                $insert_data[] = [
                                    'user_id' => $uid,
                                    'post_id' => $post_id,
                                    'expect_time' => Carbon::createFromTimestamp((int)($timestap / 1000)),
                                    'refresh_time' => null,
                                    'balance_cost' => $post_refresh_cost,
                                    'status' => 0
                                ];
                            }
                            WxPostsWeightRefresh::insert($insert_data);

                        }else{
                            DB::rollBack();
                            return $this->fail(200012);
                        }
                    }else{
                        $pay_res = UserUtils::update_user_financial($uid, 21, $the_option['price'], '您花费￥'.$the_option['price'].'推广了笔记'.$post_id.'(增加时长：'.$the_option['tip'].')');
                        if($pay_res){
                            $the_weight = $the_post->weight;
                            if($the_weight < time()){
                                $the_weight = time();
                            }
                            $the_weight += $the_option['hour'] * 3600;

                            WxPost::withoutSyncingToSearch(function () use ($post_id, $the_weight) {
                                WxPost::where('id', $post_id)->update(['weight'=>timetostr($the_weight)]);
                            });
                        }else{
                            DB::rollBack();
                            return $this->fail(200012);
                        }
                    }

                }
                WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                // 创建订单
                DB::commit();
                return $this->success(['tip'=>'恭喜，推广成功']);
            }
            else if (_array_key($order, 'type', 0) == 7) {
                // 付费圈子
                if(_empty_(_array_key($order, 'circle_id', 0))){
                    return $this->fail(200004);
                }
                $circle_id = $order['circle_id'];
                $circle = WxCircle::find($circle_id);
                if(_empty_($circle)){
                    return $this->fail(200003);
                }
                $order['price'] = $circle->follow_pay_num;
                $follow_pay_credit = $circle->follow_pay_credit;
                if($follow_pay_credit != 1){
                    return $this->fail(200004, [], '改接口仅处理余额付费'.env('circle_call', '圈子'));
                }
                // 修改使用金币的数量
                if($order['price'] <= $coin_blance){
                    $coin_blance = $order['price'];
                    $order['coins_num'] = (int)($coin_blance * $coin_rate);
                }

                if($order['coins_num'] > 0){
                    $coin_pay_percent_every = _between_(Settings::get('app_coin_pay_percent_every', 30), 0, 100);
                    if($coin_pay_percent_every > 0){
                        if( ($order['price'] * $coin_pay_percent_every / 100) < $coin_blance ){
                            DB::rollBack();
                            return $this->fail(200004, [], Settings::get('app_coin_name', '硬币').'抵扣不能超过'.$coin_pay_percent_every.'%');
                        }
                    }
                }

                if($balance - $order['price'] + $coin_blance < 0){
                    return $this->fail(200012);
                }
                $platform_division = _between_(Settings::get('app_circle_follow_pay_division', 0), 0, 100);
                $platform_reward = round($platform_division * $order['price'] / 100, 2);
                $circle_user_reward = round($order['price'] - $platform_reward, 2);

                $orderModel = $this->createOrder($uid,7,'加入付费'.env('circle_call', '圈子'),$order['price'],$order['price'],$orderSn);
                if($order['coins_num'] > 0){
                    $need_pay_price = $order['price'] - $coin_blance;
                    if($need_pay_price < 0.01){
                        // 金币直接结清
                        $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], '付费加入「'.$circle->circle_name.'」'.env('circle_call', '圈子'). $order['coins_num']. Settings::get('app_coin_name', '硬币') . '抵扣了￥'.$coin_blance.'）：金币-'.$order['coins_num']);
                        if($pay_res2){
                            $r = WxCircleRepositores::userFollowCircle($uid, $circle->id, Carbon::now()->addDays((int)$circle->follow_pay_duration)->toDateTimeString());
                            if($r){
                                if($circle_user_reward >= 0.01){
                                    $pay_res_ = UserUtils::update_user_financial($circle->user_id, 23, $circle_user_reward, '有新的用户(id: '.$uid.')加入您的付费'.env('circle_call', '圈子').'，扣掉平台分成'.$platform_division.'%，您获得'.$circle_user_reward.'余额。');
                                }
                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                        }
                    }else{
                        $pay_res = UserUtils::update_user_financial($uid, 22, $need_pay_price, '您花费了￥'.$need_pay_price.'余额+'.$order['coins_num'].Settings::get('app_coin_name', '硬币').'加入了「'.$circle->circle_name.'」'.env('circle_call', '圈子'));
                        if($pay_res){
                            $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], '加入「'.$circle->circle_name.'」'.env('circle_call', '圈子').'（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'. Settings::get('app_coin_name', '硬币') .'-'.$order['coins_num']);
                            if($pay_res2){
                                $r = WxCircleRepositores::userFollowCircle($uid, $circle->id, Carbon::now()->addDays((int)$circle->follow_pay_duration)->toDateTimeString());
                                if($r){
                                    if($circle_user_reward >= 0.01){
                                        $pay_res_ = UserUtils::update_user_financial($circle->user_id, 23, $circle_user_reward, '有新的用户(id: '.$uid.')加入您的付费'.env('circle_call', '圈子').'，扣掉平台分成'.$platform_division.'%，您获得'.$circle_user_reward.'余额。');
                                    }
                                }else{
                                    DB::rollBack();
                                    return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                                }
                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200012);
                        }
                    }
                }else{
                    $pay_res = UserUtils::update_user_financial($uid, 22, $order['price'], '您花费了￥'.$order['price'].'余额加入了「'.$circle->circle_name.'」'.env('circle_call', '圈子'));
                    if($pay_res){
                        $r = WxCircleRepositores::userFollowCircle($uid, $circle->id, Carbon::now()->addDays((int)$circle->follow_pay_duration)->toDateTimeString());
                        if($r){
                            if($circle_user_reward >= 0.01){
                                $pay_res_ = UserUtils::update_user_financial($circle->user_id, 23, $circle_user_reward, '有新的用户(id: '.$uid.')加入您的付费'.env('circle_call', '圈子').'，扣掉平台分成'.$platform_division.'%，您获得'.$circle_user_reward.'余额。');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200011, [], '余额不足');
                        }
                    }else{
                        DB::rollBack();
                        return $this->fail(200012);
                    }
                }

                WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                // 创建订单
                DB::commit();
                return $this->success(['tip'=>'恭喜，成功加入「'.$circle->circle_name.'」'.env('circle_call', '圈子').'，付费时长：'.$circle->follow_pay_duration.'天']);
            }else if (_array_key($order, 'type', 0) == 9) {
                // 购买模块
                if(get_mini_domain() == 'mini.minisns.cn'){
                    if(_empty_(_array_key($order, 'num', ''), true) || _empty_(_array_key($order, 'domain', ''))){
                        DB::rollBack();
                        return $this->fail(200004);
                    }
                    $domain = _array_key($order, 'domain', '');
                    // todo:
                    $body = '购买模块'.$order['num'];
                    $r['body'] = $body;
                    $model_paycode_map = [
                        1 => 2473,
                        2 => 2474,
                        3 => 2477,
                        4 => 2475,
                        5 => 2472,
                        6 => 2476,
                        7 => 2478,
                        8 => 2479,
                        9 => 2480,
                        10 => 2481,
                        11 => 2482,
                        12 => 2483,
                        13 => 2733,
                        14 => 2484,
                        15 => 2794,
                        16 => 2680,
                        17 => 2492,
                        18 => 2551,
                        19 => 2573,
                        20 => 2669,
                        21 => 2715,
                        22 => 2719,
                        23 => 2722,
                        24 => 2729,
                        25 => 2776,
                        26 => 2740,
                        27 => 2748,
                        28 => 2797,
                        29 => 2805,
                        30 => 2817,
                        31 => 2824,
                        32 => 2886,
                        33 => 2895,
                        34 => 2897,
                        36 => 2908,
                        0 => 2899,
                    ];
                    if(!isset($model_paycode_map[$order['num']])){
                        DB::rollBack();
                        return $this->fail(200003, [], '没有对应的模块');
                    }
                    if(_empty_(_array_key($order, 'domain', ''))){
                        $domain_auth = WxDomainAuth::where('user_id', $uid)->first();
                    }else{
                        $domain_auth = WxDomainAuth::where('domain_1', $domain)->orWhere('domain_2', $domain)
                            ->orWhere('domain_3', $domain)->orWhere('domain_4', $domain)
                            ->orWhere('domain_5', $domain)->orWhere('domain_6', $domain)
                            ->orWhere('domain_7', $domain)->first();
                    }
                    if($domain_auth){
                        // 检查这个用户需不需要购买该模块
                        $base_pays = explode(',', $domain_auth->pays);
                        if(in_array($order['num'], $base_pays)){
                            DB::rollBack();
                            return $this->fail(200010, [], '该用户已经拥有模块'.$order['num'].'的授权，无需重复购买');
                        }
                    }else{
                        // 没有授权的情况怎么办
                        if(_array_key($order, 'user_id', 0) > 0){

                        }else{
                            DB::rollBack();
                            return $this->fail(200004, [], '缺少user_id参数');
                        }
                    }

                    if($is_vip){
                        $total_fee = WxShopGoodsProduct::where('goods_id', $model_paycode_map[$order['num']])->value('vip_price');
                    }else{
                        $total_fee = WxShopGoodsProduct::where('goods_id', $model_paycode_map[$order['num']])->value('price');
                    }


                    // 判断能否代理价格
                    $is_agent_price = false;
                    $my_domain_auth = WxDomainAuth::where('user_id', $uid)->first();
                    // 条件一：自己有授权
                    if($my_domain_auth){
                        if($domain_auth){
                            // 条件二：不是给自己买模块
                            if($my_domain_auth->id != $domain_auth->id){
                                $is_agent_price = true;
                            }
                        }else{
                            // 自己有授权，但这次不是自己的
                            $is_agent_price = true;
                        }
                    }

                    if($is_agent_price){
                        if($order['num'] > 0){
                            $total_fee = round(0.8 * $total_fee, 2);
                        }else{
                            $total_fee = 300;
                        }
                    }
                    // user_id 应对利用域名查询不出来的情况
                    $orderModel = $this->createOrder($uid,9,$body,$total_fee,$total_fee,$orderSn, serialize(['num'=>$order['num'], 'domain'=>_array_key($order, 'domain', ''), 'user_id'=>_array_key($order, 'user_id', 0)]));
                    $pay_res = UserUtils::update_user_financial($uid, 27, $total_fee, '您花费了￥'.$total_fee.'余额购买了「模块'.$order['num'].'」');
                    if($pay_res){
                        if($domain_auth){
                            $base_pays = explode(',', $domain_auth->pays);
                            $base_pays[] = $order['num'];
                            $base_pays = array_unique($base_pays);
                            if($domain_auth){
                                WxDomainAuth::where('id', $domain_auth->id)->update(['pays' => implode(',', $base_pays)]);
                            }

                            if($order['num'] == 0){
                                if($domain_auth && $domain_auth->user_id != $uid){
                                    WxUser::where('id', $domain_auth->user_id)->update([
                                        'who' => $uid
                                    ]);
                                }
                            }

                        }else{
                            // 还有一种情况该用户已经有授权，只是不是这个域名
                            // todo:

                            if(_array_key($order, 'user_id', 0) > 0){
                                // 新建授权
                                $model = new WxDomainAuth();
                                $model->user_id = $order['user_id'];
                                $model->domain_1 = $order['domain'];
                                $model->tenant_1 = '0,999';
                                $model->pays = $order['num'];
                                $r = $model->save();
                                if($order['num'] == 0){
                                    if($order['user_id'] != $uid){
                                        WxUser::where('id', $model->user_id)->update([
                                            'who' => $uid
                                        ]);
                                    }
                                }
                            }
                        }

                        // 分账
                        if($model_paycode_map[$order['num']] > 0){
                            $users_ledger = WxShopGoods::where('id', $model_paycode_map[$order['num']])->value('users_ledger');
                            if(!_empty_($users_ledger)){
                                $users_ledger = json_decode($users_ledger, true);
                                if(!_empty_($users_ledger)){
                                    foreach ($users_ledger as $item){
                                        if(_empty_(_array_key($item, 'user_id', 0)) || _empty_(_array_key($item, 'rate', 0))){
                                            continue;
                                        }
                                        if($total_fee > 0){
                                            $recharge_division = round(  $total_fee * $item['rate'] * 0.01, 2);
                                            if($recharge_division >= 0.01){
                                                UserUtils::update_user_financial($item['user_id'], 20, $recharge_division,
                                                    '您获得一笔来自商品(id：<a href="/pagesA/shop/goods-details/goods-details?id='.$model_paycode_map[$order['num']].'">'.$model_paycode_map[$order['num']].'</a>)的分账，该商品共消费￥'.$total_fee.'，您获得其中'.$item['rate'].'%');
                                            }
                                        }
                                    }
                                }

                            }
                        }

                    }else{
                        DB::rollBack();
                        return $this->fail(200012, [], '余额不足');
                    }
                    WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                    DB::commit();
                    return $this->success(['tip'=>'您花费了￥'.$total_fee.'余额购买了「模块'.$order['num'].'」']);
                }
            }else if (_array_key($order, 'type', 0) == 10) {
                if(_empty_(_array_key($order, 'user_id', 0)) || _empty_(_array_key($order, 'user_state', 0))){
                    return $this->fail(200004);
                }

                $user_id = $order['user_id'];
                $the_user = WxUser::find($user_id);
                if(_empty_($the_user)){
                    return $this->fail(200003);
                }

                if($order['user_state'] != $the_user->user_state){
                    return $this->fail(200004, [], '参数检验不合法，请刷新重试');
                }

                $order['price'] = 0;
                $body = '';
                if($the_user->user_state === 2){
                    $ban_until = get_user_meta($the_user->id, 'ban_until', 's');
                    if(time() > $ban_until){
                        // 解除封号
                        if(UserUtils::unlock_user($the_user, 2)){
                            $the_user->state_tip = '正常用户';
                            $the_user->user_state = 0;
                        }
                    }
                    if($ban_until && $the_user->user_state === 2){
                        $ban_until_ = Carbon::createFromTimestamp($ban_until);
                        $secondsDifference = $ban_until_->diffInSeconds(Carbon::now());
                        $hoursDifference = round($secondsDifference / 3600, 2);

                        $tmp_tenant_id = -1;
                        if($__MINI_GLOBAL_TENANT_ID__ != $the_user->tenant_id){
                            $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                            $__MINI_GLOBAL_TENANT_ID__ = $the_user->tenant_id;
                        }
                        $order['price'] = round($hoursDifference * Settings::get('app_unban_one_hour_balance', 1.0, true), 2);
                        if($tmp_tenant_id > 0){
                            $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
                        }

                        if($the_user->id == $uid){
                            $body = '自助解封账号';
                        }else{
                            $body = '帮他人(uid：'.$the_user->id.')解封账号';
                        }
                    }
                }else if($the_user->user_state === 3){
                    $mute_until = get_user_meta($the_user->id, 'mute_until', 's');
                    if(time() > $mute_until){
                        // 解除禁言
                        if(UserUtils::unlock_user($the_user, 3)){
                            $the_user->state_tip = '正常用户';
                            $the_user->user_state = 0;
                        }
                    }
                    if($mute_until && $the_user->user_state === 3){
                        $mute_until_ = Carbon::createFromTimestamp($mute_until);
                        $secondsDifference = $mute_until_->diffInSeconds(Carbon::now());
                        $hoursDifference = round($secondsDifference / 3600, 2);

                        $tmp_tenant_id = -1;
                        if($__MINI_GLOBAL_TENANT_ID__ != $the_user->tenant_id){
                            $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                            $__MINI_GLOBAL_TENANT_ID__ = $the_user->tenant_id;
                        }
                        $order['price'] = round($hoursDifference * Settings::get('app_unmute_one_hour_balance', 0.5, true), 2);
                        if($tmp_tenant_id > 0){
                            $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
                        }


                        if($the_user->id == $uid){
                            $body = '自助解除禁言';
                        }else{
                            $body = '帮他人(uid：'.$the_user->id.')解除禁言';
                        }
                    }
                }else{
                    return $this->fail(200009, [], '无法解除');
                }
                if(_empty_($order['price'])){
                    return $this->fail(200009, [], '无法解除');
                }
                // 修改使用金币的数量
                if($order['price'] <= $coin_blance){
                    $coin_blance = $order['price'];
                    $order['coins_num'] = (int)($coin_blance * $coin_rate);
                }

                if($order['coins_num'] > 0){
                    $coin_pay_percent_every = _between_(Settings::get('app_coin_pay_percent_every', 30), 0, 100);
                    if($coin_pay_percent_every > 0){
                        if( ($order['price'] * $coin_pay_percent_every / 100) < $coin_blance ){
                            DB::rollBack();
                            return $this->fail(200004, [], Settings::get('app_coin_name', '硬币').'抵扣不能超过'.$coin_pay_percent_every.'%');
                        }
                    }
                }

                if($balance - $order['price'] + $coin_blance < 0){
                    return $this->fail(200012);
                }

                $orderModel = $this->createOrder($uid,10,$body,$order['price'],$order['price'],$orderSn, serialize(['user_id'=>$the_user->id, 'user_state' => $the_user->user_state]));
                if($order['coins_num'] > 0){
                    $need_pay_price = $order['price'] - $coin_blance;
                    if($need_pay_price < 0.01){
                        // 金币直接结清
                        $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], $body . $order['coins_num']. Settings::get('app_coin_name', '硬币') . '抵扣了￥'.$coin_blance.'）：金币-'.$order['coins_num']);
                        if($pay_res2){
                            UserUtils::unlock_user($the_user, $the_user->user_state);
                        }else{
                            DB::rollBack();
                            return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                        }
                    }else{
                        $pay_res = UserUtils::update_user_financial($uid, 30, $need_pay_price, '您花费了￥'.$need_pay_price.'余额+'.$order['coins_num'].Settings::get('app_coin_name', '硬币').$body);
                        if($pay_res){
                            $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], $body.'（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'. Settings::get('app_coin_name', '硬币') .'-'.$order['coins_num']);
                            if($pay_res2){
                                UserUtils::unlock_user($the_user, $the_user->user_state);
                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200012);
                        }
                    }
                }else{
                    $pay_res = UserUtils::update_user_financial($uid, 30, $order['price'], '您花费了￥'.$order['price'].'余额'.$body);
                    if($pay_res){
                        UserUtils::unlock_user($the_user, $the_user->user_state);
                    }else{
                        DB::rollBack();
                        return $this->fail(200012);
                    }
                }
                if($uid != $the_user->id){
                    UserUtils::assistant_notice($the_user->id, '用户(<a href="/pages/user/user?id='.$uid.'">'.UserUtils::get_cached_user_name($uid).' id:'.$uid.'</a>)花费了￥'.$order['price'].'帮您解除了账号的'.($the_user->user_state == 2 ? '封号' : '禁言').'限制');
                }
                WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                // 创建订单
                DB::commit();
                return $this->success(['tip'=>'恭喜，'.$body.'成功']);
            }else if (_array_key($order, 'type', 0) == 11) {
                if(_empty_(_array_key($order, 'object_id', 0)) || _empty_(_array_key($order, 'is_wechat_account', 0), true) || _empty_(_array_key($order, 'is_phone', 0), true)){
                    return $this->fail(200004);
                }
                $object_id = $order['object_id'];
                $is_wechat_account = _empty_default_(_array_key($order, 'is_wechat_account', 0), 0);
                $is_phone = _empty_default_(_array_key($order, 'is_phone', 0), 0);
                $the_user = WxUser::find($object_id);
                if(_empty_($the_user)){
                    return $this->fail(200003);
                }
                if($the_user->id == $uid){
                    return $this->fail(200000, [], '双方账号不能相同');
                }
                $contact_apply = WxUserContactApply::where('user_id', $uid)->where('object_id', $the_user->id)->first();
                $user_settings = WxUserSetting::where('user_id', $the_user->id)->first();
                if(_empty_($user_settings)){
                    return $this->fail(200000, [], '请退出登录，重新登录一下试试');
                }

                if($contact_apply){
                    if($contact_apply->status == 0){
                        return $this->fail(200000, [], '你已经申请过了该用户的联系方式');
                    }
                }


                $total_fee = 0;
                $body = '';
                if(_empty_($contact_apply) || $contact_apply->status == 2){
                    if($is_wechat_account == 1){
                        if($user_settings->privacy_get_my_wechat != 5){
                            return [
                                'code'=>200000,
                                'msg' => '该用户未开放微信号'
                            ];
                        }else{
                            $total_fee += $user_settings->privacy_get_my_wechat_pay;
                            if(!_empty_($body)){
                                $body .= '、';
                            }
                            $body .= 'v';
                        }
                    }
                    if($is_phone == 1){
                        if($user_settings->privacy_get_my_phone != 5){
                            return $this->fail(200000, [], '该用户未开放手机号');
                        }else{
                            $total_fee += $user_settings->privacy_get_my_phone_pay;
                            if(!_empty_($body)){
                                $body .= '、';
                            }
                            $body .= 'tel';
                        }
                    }
                }else{
                    if($is_wechat_account == 1){
                        if($contact_apply->is_wechat_account != 1){
                            if($user_settings->privacy_get_my_wechat != 5){
                                return $this->fail(200000, [], '该用户未开放微信号');
                            }else{
                                $total_fee += $user_settings->privacy_get_my_wechat_pay;
                                if(!_empty_($body)){
                                    $body .= '、';
                                }
                                $body .= 'v';
                            }
                        }else{
                            $is_wechat_account = 0;
                        }
                    }
                    if($is_phone == 1){
                        if($contact_apply->is_phone != 1){
                            if($user_settings->privacy_get_my_phone != 5){
                                return $this->fail(200000, [], '该用户未开放手机号');
                            }else{
                                $total_fee += $user_settings->privacy_get_my_phone_pay;
                                if(!_empty_($body)){
                                    $body .= '、';
                                }
                                $body .= 'tel';
                            }
                        }else{
                            $is_phone = 0;
                        }
                    }
                }

                $reason = StrUtils::limit(strip_tags(trim(_empty_default_(_array_key($order, 'reason', ''), ''))));
                $order['price'] = $total_fee;
                // 修改使用金币的数量
                if($order['price'] <= $coin_blance){
                    $coin_blance = $order['price'];
                    $order['coins_num'] = (int)($coin_blance * $coin_rate);
                }

                if($order['coins_num'] > 0){
                    $coin_pay_percent_every = _between_(Settings::get('app_coin_pay_percent_every', 30), 0, 100);
                    if($coin_pay_percent_every > 0){
                        if( ($order['price'] * $coin_pay_percent_every / 100) < $coin_blance ){
                            DB::rollBack();
                            return $this->fail(200004, [], Settings::get('app_coin_name', '硬币').'抵扣不能超过'.$coin_pay_percent_every.'%');
                        }
                    }
                }

                if($balance - $order['price'] + $coin_blance < 0){
                    return $this->fail(200012);
                }

                $orderModel = $this->createOrder($uid,11,$body,$order['price'],$order['price'],$orderSn, serialize(['object_id'=>$the_user->id, 'is_wechat_account'=>$is_wechat_account == 1 ? 1 : 0, 'is_phone' => $is_phone == 1 ? 1 : 0, 'reason'=>$reason]));
                if($order['coins_num'] > 0){
                    $need_pay_price = $order['price'] - $coin_blance;
                    if($need_pay_price < 0.01){
                        // 金币直接结清
                        $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], $body . $order['coins_num']. Settings::get('app_coin_name', '硬币') . '抵扣了￥'.$coin_blance.'）：金币-'.$order['coins_num']);
                        if($pay_res2){
                            OrderUtils::order_obtains($orderModel);
                        }else{
                            DB::rollBack();
                            return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                        }
                    }else{
                        $pay_res = UserUtils::update_user_financial($uid, 32, $need_pay_price, '您花费了￥'.$need_pay_price.'余额+'.$order['coins_num'].Settings::get('app_coin_name', '硬币').$body);
                        if($pay_res){
                            $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order['coins_num'], $body.'（'. $order['coins_num'].Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'. Settings::get('app_coin_name', '硬币') .'-'.$order['coins_num']);
                            if($pay_res2){
                                OrderUtils::order_obtains($orderModel);
                            }else{
                                DB::rollBack();
                                return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                            }
                        }else{
                            DB::rollBack();
                            return $this->fail(200012);
                        }
                    }
                }else{
                    $pay_res = UserUtils::update_user_financial($uid, 32, $order['price'], '您花费了￥'.$order['price'].'余额'.$body);
                    if($pay_res){
                        OrderUtils::order_obtains($orderModel);
                    }else{
                        DB::rollBack();
                        return $this->fail(200012);
                    }
                }
                WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                // 创建订单
                DB::commit();
                return $this->success(['tip'=>'恭喜，'.$body.'成功']);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200002);
        }
    }

    private function _create_order(Request $request){

        DB::beginTransaction();
        try {
            $r = ['code'=>0, 'orderSn'=>'', 'total_fee'=>0, 'body'=>'', 'msg'=>''];

            $uid = $request->uid;
            $type = $request->type;
            $parame = $request->parame;
            $orderSn = Utils::getSn(1);
            global $__MINI_GLOBAL_TENANT_ID__;
            // 开会员
            if ($type == 1) {
                if(_empty_(_array_key($parame, 'price', 0)) || _empty_(_array_key($parame, 'days', 0))){
                    return $this->fail(200004);
                }
                $total_fee = $parame['price'];
                $r['body'] = '开通会员'.$parame['days'].'天';
                $vip_options = json_decode(Settings::get('app_vip_options', '[]'), true);
                if(_empty_($vip_options)){
                    return [
                        'code'=>200004,
                        'msg' => '管理员暂未配置会员套餐'
                    ];
                }
                $flag = false;
                foreach ($vip_options as $option){
                    if($option && $option['days'] == $parame['days'] && $option['price'] == $parame['price']){
                        $flag = true;
                        break;
                    }
                }
                if($flag){
                    $this->createOrder($uid,1,'开通会员'.$parame['days'].'天',$total_fee,$total_fee,$orderSn);
                }else{
                    return [
                        'code'=>200004,
                        'msg' => '管理员暂未配置￥'.$parame['price'].'的'.$parame['days'].'天套餐'
                    ];
                }
            }else if ($type == 2) {

                $body = '充电';
                $r['body'] = '充电';
                $total_fee = $parame['rewardPrice'];
                $parame = serialize($parame);
                // 创建订单
                $this->createOrder($uid,2,$body,$total_fee,$total_fee,$orderSn,$parame);

            }else if ($type == 3) {

                $body = '余额充值';
                $r['body'] = '余额充值';
                $total_fee = $parame['recharge'];
                $recharge_list_arr = Settings::get('app_balance_recharge_list', []);
                $flag = false;
                if($recharge_list_arr){
                    foreach ($recharge_list_arr as $option){
                        if($option['rmb'] == $total_fee){
                            $flag = true;
                        }
                    }
                }
                if($flag){
                    // 创建订单
                    $this->createOrder($uid,3,$body,$total_fee,$total_fee,$orderSn);
                }else{
                    return [
                        'code'=>200004,
                        'msg' => '充值套餐未包含'.$total_fee.'的充值'
                    ];
                }
            }else if( $type == 6){
                // 付费推广
                $is_promotion_refresh = false;
                $time_list = [];
                if(_array_key($parame, 'is_refresh', 0) == 1){
                    if( _empty_(_array_key($parame, 'post_id', 0)) || _empty_(_array_key($parame, 'time_list', [])) ){
                        return $this->fail(200004);
                    }
                    $is_promotion_refresh = true;
                }else{
                    if(_empty_(_array_key($parame, 'post_id', 0)) || _empty_(_array_key($parame, 'index', 0), true)){
                        return [
                            'code'=>200004,
                            'msg' => '缺少必要的参数'
                        ];
                    }
                }
                $post_id = _abs($parame['post_id']);
                $the_post = WxPost::where('id', $post_id)->where([['is_examine' ,'=', 1], ['posts_state' , '=', 0]])->first();
                if(!$the_post){
                    return [
                        'code'=>200004,
                        'msg' => '笔记不存在或非正常推送状态'
                    ];
                }
                $__MINI_GLOBAL_TENANT_ID__ = $the_post->tenant_id;

                if($is_promotion_refresh){
                    $time_list = _array_key($parame, 'time_list', []);
                    if(!is_array($time_list)){
                        return $this->fail(200004);
                    }
                    $the_order_price = bcdiv(Settings::get('app_promoted_post_refresh_cost', 1.0, true) * count($time_list), 1, 2);
                    $order_info_des = '笔记推广自动刷新'.count($time_list).'次';
                }else{
                    $index_option = $parame['index'] ?? 0;

                    $tmp_tenant_id = -1;
                    if($__MINI_GLOBAL_TENANT_ID__ != $the_post->tenant_id){
                        $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                        $__MINI_GLOBAL_TENANT_ID__ = $the_post->tenant_id;
                    }
                    $post_options = Settings::get('app_promoted_post_options', [], true);
                    if($tmp_tenant_id > 0){
                        $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
                    }


                    if(_empty_($post_options) || !isset($post_options[$index_option])){
                        return [
                            'code'=>200004,
                            'msg' => '后台未配置index为'.$index_option.'的付费推广套餐'
                        ];
                    }
                    $the_option = $post_options[$index_option];
                    if($the_option['credit_type'] != 1){
                        return [
                            'code'=>200004,
                            'msg' => '该接口只能进行余额付费推广'
                        ];
                    }
                    $the_order_price = $the_option['price'];
                    $order_info_des = '笔记付费置顶'.$the_option['hour'].'小时';
                }

                if($the_order_price >= 0.01){
                    if($is_promotion_refresh){
                        $body = StrUtils::limit('付费推广笔记（id:'.$the_post->id.'）自动刷新'.count($time_list).'次');
                        $parame = serialize(['post_id'=>$the_post->id, 'time_list'=>json_encode($time_list)]);
                    }else{
                        $body = StrUtils::limit('付费推广笔记（id:'.$the_post->id.'）'.$the_option['tip']);
                        $parame = serialize(['post_id'=>$the_post->id, 'index'=>$index_option, 'hour'=>$the_option['hour'], 'tip'=>$the_option['tip'], 'price'=>$the_option['price'], 'credit_type'=>$the_option['credit_type']]);
                    }
                    $r['body'] = $body;
                    $total_fee = $the_order_price;
                    // 创建订单
                    $this->createOrder($uid,6,$body,$total_fee,$total_fee,$orderSn,$parame);
                }else{
                    return [
                        'code'=>200004,
                        'msg' => '付费推广小于0.01,无法支付'
                    ];
                }
            }else if( $type == 7){
                // 付费圈子
                if(_empty_(_array_key($parame, 'circle_id', 0))){
                    return [
                        'code'=>200004,
                        'msg' => '缺少circle_id参数'
                    ];
                }

                $circle_id = $parame['circle_id'];
                $circle = WxCircle::find($circle_id);
                if(_empty_($circle)){
                    return [
                        'code'=>200003,
                        'msg' => '圈子实际不存在或状态不对'
                    ];
                }
                $follow_pay_credit = $circle->follow_pay_credit;
                if($follow_pay_credit != 1){
                    return [
                        'code'=>200004,
                        'msg' => '改接口仅处理余额付费圈子'
                    ];
                }

                if($circle->follow_pay_num >= 0.01){
                    $body = StrUtils::limit('加入圈子('. $circle->circle_name . '/' . $circle->follow_pay_duration . '天)', 20);
                    $r['body'] = $body;
                    $total_fee = $circle->follow_pay_num;
                    $parame = serialize($parame);
                    // 创建订单
                    $this->createOrder($uid,7,$body,$total_fee,$total_fee,$orderSn,$parame);
                }else{
                    return [
                        'code'=>200004,
                        'msg' => '圈子付费数额小于0.01,无法支付'
                    ];
                }
            }else if( $type == 8){
                $body = '店铺保证金充值';
                $r['body'] = $body;
                $total_fee = $parame['recharge'];
                $this->createOrder($uid,8,$body,$total_fee,$total_fee,$orderSn);
            }else if( $type == 9){
                // 购买模块
                if(get_mini_domain() == 'mini.minisns.cn'){
                    // todo:

                    $body = '购买模块'.$parame['num'];
                    $r['body'] = $body;
                    $model_paycode_map = [
                        1 => 2473,
                        2 => 2474,
                        3 => 2477,
                        4 => 2475,
                        5 => 2472,
                        6 => 2476,
                        7 => 2478,
                        8 => 2479,
                        9 => 2480,
                        10 => 2481,
                        11 => 2482,
                        12 => 2483,
                        13 => 2733,
                        14 => 2484,
                        15 => 2794,
                        16 => 2680,
                        17 => 2492,
                        18 => 2551,
                        19 => 2573,
                        20 => 2669,
                        21 => 2715,
                        22 => 2719,
                        23 => 2722,
                        24 => 2729,
                        25 => 2776,
                        26 => 2740,
                        27 => 2748,
                        28 => 2797,
                        29 => 2805,
                        30 => 2817,
                        31 => 2824,
                        32 => 2886,
                        33 => 2895,
                        34 => 2897,
                        36 => 2908,
                        0 => 2899
                    ];
                    $total_fee = WxShopGoodsProduct::where('goods_id', $model_paycode_map[$parame['num']])->value('price');
                    // user_id 应对利用域名查询不出来的情况
                    $this->createOrder($uid,9,$body,$total_fee,$total_fee,$orderSn, serialize(['num'=>$parame['num'], 'domain'=>_array_key($parame, 'domain', ''), 'user_id'=>_array_key($parame, 'user_id', 0)]));
                }
            }else if( $type == 10){
                global $__MINI_GLOBAL_CURRENT_USER_ID__;
                $user_id = $parame['user_id'];
                if(_empty_($user_id)){
                    return [
                        'code'=>200001,
                        'msg' => '缺少user_id参数'
                    ];
                }
                $front_user_state = $parame['user_state'];
                $the_user = WxUser::find($user_id);
                if(_empty_($the_user)){
                    return [
                        'code'=>200004,
                        'msg' => 'user_id无效'
                    ];
                }
                if($front_user_state != $the_user->user_state){
                    return [
                        'code'=>200004,
                        'msg' => '参数检验不合法，请刷新重试'
                    ];
                }
                $total_fee = 0;
                $body = '';
                if($the_user->user_state === 2){
                    $ban_until = get_user_meta($the_user->id, 'ban_until', 's');
                    if(time() > $ban_until){
                        // 解除封号
                        if(UserUtils::unlock_user($the_user, 2)){
                            $the_user->state_tip = '正常用户';
                            $the_user->user_state = 0;
                        }
                    }
                    if($ban_until && $the_user->user_state === 2){
                        $ban_until_ = Carbon::createFromTimestamp($ban_until);
                        $secondsDifference = $ban_until_->diffInSeconds(Carbon::now());
                        $hoursDifference = round($secondsDifference / 3600, 2);

                        $tmp_tenant_id = -1;
                        if($__MINI_GLOBAL_TENANT_ID__ != $the_user->tenant_id){
                            $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                            $__MINI_GLOBAL_TENANT_ID__ = $the_user->tenant_id;
                        }
                        $total_fee = round($hoursDifference * Settings::get('app_unban_one_hour_balance', 1.0, true), 2);
                        if($tmp_tenant_id > 0){
                            $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
                        }

                        if($the_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                            $body = '自助解封账号';
                        }else{
                            $body = '帮他人(uid：'.$the_user->id.')解封账号';
                        }
                    }
                }else if($the_user->user_state === 3){
                    $mute_until = get_user_meta($the_user->id, 'mute_until', 's');
                    if(time() > $mute_until){
                        // 解除禁言
                        if(UserUtils::unlock_user($the_user, 3)){
                            $the_user->state_tip = '正常用户';
                            $the_user->user_state = 0;
                        }
                    }
                    if($mute_until && $the_user->user_state === 3){
                        $mute_until_ = Carbon::createFromTimestamp($mute_until);
                        $secondsDifference = $mute_until_->diffInSeconds(Carbon::now());
                        $hoursDifference = round($secondsDifference / 3600, 2);

                        global $__MINI_GLOBAL_TENANT_ID__;
                        $tmp_tenant_id = -1;
                        if($__MINI_GLOBAL_TENANT_ID__ != $the_user->tenant_id){
                            $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                            $__MINI_GLOBAL_TENANT_ID__ = $the_user->tenant_id;
                        }
                        $total_fee = round($hoursDifference * Settings::get('app_unmute_one_hour_balance', 0.5, true), 2);
                        if($tmp_tenant_id > 0){
                            $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
                        }


                        if($the_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                            $body = '自助解除禁言';
                        }else{
                            $body = '帮他人(uid：'.$the_user->id.')解除禁言';
                        }
                    }
                }else{
                    return [
                        'code'=>200009,
                        'msg' => '无法解除'
                    ];
                }
                $r['body'] = $body;
                if(_empty_($total_fee) || _empty_($body)){
                    return [
                        'code'=>200009,
                        'msg' => '无需解除'
                    ];
                }
                $this->createOrder($uid,10,$body,$total_fee,$total_fee,$orderSn, serialize(['user_id'=>$the_user->id, 'user_state'=>$the_user->user_state]));
            }else if( $type == 11){
                global $__MINI_GLOBAL_CURRENT_USER_ID__;
                $object_user_id = $parame['object_id'];
                if(_empty_($object_user_id)){
                    return [
                        'code'=>200001,
                        'msg' => '缺少user_id参数'
                    ];
                }
                $the_user = WxUser::find($object_user_id);
                if(_empty_($the_user)){
                    return [
                        'code'=>200004,
                        'msg' => 'user_id无效'
                    ];
                }
                $is_wechat_account = $parame['is_wechat_account'];
                $is_phone = $parame['is_phone'];
                if(_empty_($is_wechat_account, true)){
                    return [
                        'code'=>200001,
                        'msg' => '缺少is_wechat_account参数'
                    ];
                }
                if(_empty_($is_phone, true)){
                    return [
                        'code'=>200001,
                        'msg' => '缺少is_phone参数'
                    ];
                }
                if($the_user->id == $__MINI_GLOBAL_CURRENT_USER_ID__){
                    return [
                        'code'=>200004,
                        'msg' => '双方账号不能相同'
                    ];
                }
                $contact_apply = WxUserContactApply::where('user_id', $__MINI_GLOBAL_CURRENT_USER_ID__)->where('object_id', $the_user->id)->first();
                $user_settings = WxUserSetting::where('user_id', $the_user->id)->first();
                if(_empty_($user_settings)){
                    return [
                        'code'=>200004,
                        'msg' => '请退出登录，重新登录一下试试'
                    ];
                }

                if($contact_apply){
                    if($contact_apply->status == 0){
                        return [
                            'code'=>200000,
                            'msg' => '你已经申请过了该用户的联系方式'
                        ];
                    }
                }


                $total_fee = 0;
                $body = '';
                if(_empty_($contact_apply) || $contact_apply->status == 2){
                    if($is_wechat_account == 1){
                        if($user_settings->privacy_get_my_wechat != 5){
                            return [
                                'code'=>200000,
                                'msg' => '该用户未开放微信号'
                            ];
                        }else{
                            $total_fee += $user_settings->privacy_get_my_wechat_pay;
                            if(!_empty_($body)){
                                $body .= '、';
                            }
                            $body .= 'v';
                        }
                    }
                    if($is_phone == 1){
                        if($user_settings->privacy_get_my_phone != 5){
                            return [
                                'code'=>200000,
                                'msg' => '该用户未开放手机号'
                            ];
                        }else{
                            $total_fee += $user_settings->privacy_get_my_phone_pay;
                            if(!_empty_($body)){
                                $body .= '、';
                            }
                            $body .= 'tel';
                        }
                    }
                }else{
                    if($is_wechat_account == 1){
                        if($contact_apply->is_wechat_account != 1){
                            if($user_settings->privacy_get_my_wechat != 5){
                                return [
                                    'code'=>200000,
                                    'msg' => '该用户未开放微信号'
                                ];
                            }else{
                                $total_fee += $user_settings->privacy_get_my_wechat_pay;
                                if(!_empty_($body)){
                                    $body .= '、';
                                }
                                $body .= 'v';
                            }
                        }else{
                            $is_wechat_account = 0;
                        }
                    }
                    if($is_phone == 1){
                        if($contact_apply->is_phone != 1){
                            if($user_settings->privacy_get_my_phone != 5){
                                return [
                                    'code'=>200000,
                                    'msg' => '该用户未开放手机号'
                                ];
                            }else{
                                $total_fee += $user_settings->privacy_get_my_phone_pay;
                                if(!_empty_($body)){
                                    $body .= '、';
                                }
                                $body .= 'tel';
                            }
                        }else{
                            $is_phone = 0;
                        }
                    }
                }

                $reason = StrUtils::limit(strip_tags(trim(_empty_default_(_array_key($parame, 'reason', ''), ''))));
                $body = '用户(id:'.$the_user->id.')的'.$body;
                $r['body'] = $body;
                $this->createOrder($uid,11,$body,$total_fee,$total_fee,$orderSn, serialize(['object_id'=>$the_user->id, 'is_wechat_account'=>$is_wechat_account == 1 ? 1 : 0, 'is_phone' => $is_phone == 1 ? 1 : 0, 'reason'=>$reason]));
            }
            DB::commit();

            $r['code'] = 200;
            $r['orderSn'] = $orderSn;
            $r['total_fee'] = $total_fee;
            return $r;
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getTrace());
            $r['code'] = 200002;
            return $r;
        }

    }



    /**
     * 统一下单地址
     * @param Request $request
     * @param $type 类型：1:会员 类型：2:充电 7:付费圈子
     * @return \Illuminate\Http\JsonResponse
     */
    public function order(Request $request)
    {
        $uid = $request->uid;

        $r = $this->_create_order($request);
        if($r['code'] != 200){
            return $this->fail($r['code'], [], _array_key($r, 'msg', ''));
        }

        $openid = WxUser::where('id', $uid)->value('weixin_openid');
        $appid = Settings::get('app_id');
        $mch_id = Settings::get('mch_id');
        $key = Settings::get('mch_secret');
        $out_trade_no = $r['orderSn'];

        if(_empty_($openid)){
            return $this->fail(200043, [
                'title' => '未绑定微信',
                'content' => '还没有获取到您的小程序openId，无法拉起支付',
                'confirmText' => '去绑定',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/editmine/accountbind'
            ], '未绑定微信');
        }

        return $this->payHandler($uid, 'wxpay', 'mini', $r['total_fee'], $r['body'], $out_trade_no, 1);
        // 发起支付
//        $payObject = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $r['body'], $r['total_fee']);
//        $pay_result = $payObject->pay();
//        if(_array_key($pay_result, 'return_code', '') == 'FAIL'){
//            return $this->fail(200014, [], $pay_result['return_msg']);
//        }else{
//            return $this->success($pay_result);
//        }
    }

    /**
     * app端下单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderForApp(Request $request){

        if(!in_array($request->provider, ['wxpay', 'alipay', 'apple'])){
            return $this->fail(200004, [], 'provider参数仅支持wxpay/alipay');
        }

        if(!in_array($request->pay_type, ['app', 'h5', 'yi', 'code', 'code_pc'])){
            return $this->fail(200004, [], 'pay_type参数仅支持app/h5/yi/code');
        }

        $uid = $request->uid;
        if( $request->provider == 'apple' ){
            $parame = $request->parame;
            if(_empty_($parame) || _empty_(_array_key($parame, 'productId', ''))){
                return $this->fail(200001);
            }
            $productId = _array_key($parame, 'productId', '');
            return $this->applePayHandler($uid, $productId);
        }else{
            $r = $this->_create_order($request);
            if($r['code'] != 200){
                return $this->fail($r['code'], [], _array_key($r, 'msg', ''));
            }

            // 共同的资料
            $total_fee = $r['total_fee'];
            $body = $r['body'];
            $out_trade_no = $r['orderSn'];

            $pay_type = $request->pay_type;
            global $__MINI_GLOBAL_DEVICE__;
            if($__MINI_GLOBAL_DEVICE__ == 'h5' && _empty_default_($request->h5_browser, '') == 'wxclient'){
                $pay_type = 'mp';
            }
            return $this->payHandler($uid, $request->provider, $pay_type, $total_fee, $body, $out_trade_no);
        }

    }

    public function applePayHandler($uid, $productId){
        DB::beginTransaction();
        try {

            if(strpos($productId, 'apple_pay_product_recharge') === 0){
                $orderSn = Utils::getSn(1);
                $num = (int)(str_replace('apple_pay_product_recharge_', '', $productId));
                if(!in_array($num, [1, 3, 6, 12, 28, 48, 78, 98, 128, 168, 198, 228, 298])){
                    return $this->fail(200004, [], '充值余额'.$num.'未在选项中');
                }
                // 创建订单
                $model = $this->createOrder($uid,3,'余额充值',$num,$num, $orderSn);
                if($model){
                    DB::commit();
                    return $this->success(['orderId'=>$model->id, 'productId'=>$productId, 'user_id'=>$uid, 'order_number'=>$orderSn]);
                }
            }else if(strpos($productId, 'apple_pay_product_vip') === 0){
                $orderSn = Utils::getSn(1);
                $order_price = (int)(str_replace('apple_pay_product_vip_', '', $productId));

                $vip_options = json_decode(Settings::get('app_vip_options', '[]'), true);
                if(_empty_($vip_options)){
                    return $this->fail(200004, [], '管理员暂未配置会员套餐');
                }
                $flag = false;
                $days = 0;
                foreach ($vip_options as $option){
                    if($option && $option['price'] == $order_price){
                        $flag = true;
                        $days = $option['days'];
                        break;
                    }
                }
                if(!$flag){
                    return $this->fail(200004, [], '会员套餐￥'.$order_price.'未在选项中');
                }
                // 创建订单
                $model = $this->createOrder($uid,1,'开通会员'.$days.'天',$order_price,$order_price,$orderSn);
                if($model){
                    DB::commit();
                    return $this->success(['orderId'=>$model->id, 'productId'=>$productId, 'user_id'=>$uid, 'order_number'=>$orderSn]);
                }
            }
            DB::rollBack();
            return $this->fail(200004);
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200004);
        }
    }

    /**
     * 创建订单
     */
    public function createOrder($user_id,$order_type,$order_information,$order_price,$order_pay_price,$order_number,$parame='')
    {
        $orderModel = new WxOrder();
        $orderModel->user_id = $user_id;
        $orderModel->order_type = $order_type;
        $orderModel->order_information = $order_information;
        $orderModel->order_price = $order_price;
        $orderModel->order_pay_price = $order_pay_price;
        $orderModel->order_number = $order_number;
        $orderModel->parame = $parame;
        $orderModel->save();
        return $orderModel;
    }

    public function processPayPost($uid, $post_id, $scene, $orderSn,  $coins_num, $coin_blance, $coin_rate){
        $res_arr = ['code'=>0, 'tip'=>''];
        if(_empty_($post_id) || _empty_($scene)){
            $res_arr['code'] = 200001;
            return $res_arr;
        }

        $post_obj = WxPost::where('id', $post_id)->first(['user_id','pay_content_id', 'circle_id']);
        if(_empty_($post_obj)){
            $res_arr['code'] = 200003;
            return $res_arr;
        }

        $post_user_id = $post_obj->user_id;
        $pay_content_id = $post_obj->pay_content_id;
        $circle_id = $post_obj->circle_id;

        if(_empty_($pay_content_id)){
            $res_arr['code'] = 200004;
            return $res_arr;
        }

        if($uid == $post_user_id){
            $res_arr['code'] = 200038;
            return $res_arr;
        }

        if(WxUserPay::where([
            ['user_id', '=', $uid],
            ['post_id', '=', $post_id],
            ['pay_content_id', '=', $pay_content_id]
        ])->exists()){
            $res_arr['code'] = 200035;
            return $res_arr;
        }


        $pay_content_obj = WxPostsPayContent::find($pay_content_id);
        if(_empty_($pay_content_obj)){
            $res_arr['code'] = 200003;
            return $res_arr;
        }

        $price = $pay_content_obj->price;
        $credit_type = $pay_content_obj->credit_type;
        $user = WxUser::find($uid);
        $user_name = $user->user_name;
        $is_vip = $user->is_member;
        $vip_discount = _between_(Settings::get('app_vip_paycontent_discount', 0), 0, 100);
        $vip_price_tip = '';
        if($vip_discount > 0 && $is_vip){
            if($credit_type == 0){
                $vip_price = (int)($price * ( (100 - $vip_discount) / 100));
            }else{
                $vip_price = round($price * ( (100 - $vip_discount) / 100), 2);
            }
            $vip_price_tip = '会员价';
        }else{
            $vip_price = $price;
        }

        if($credit_type == 0){
            $res_arr['code'] = 200004;
            $res_arr['tip'] = '该接口仅能购买余额付费内容';
            return $res_arr;
        }else if($credit_type == 1){
            // 修改使用金币的数量
            if($vip_price <= $coin_blance){
                $coin_blance = $vip_price;
                $coins_num = (int)($coin_blance * $coin_rate);
            }

            if($coins_num > 0){
                $coin_pay_percent_every = _between_(Settings::get('app_coin_pay_percent_every', 30), 0, 100);
                if($coin_pay_percent_every > 0){
                    if( ($vip_price * $coin_pay_percent_every / 100) < $coin_blance ){
                        $res_arr['code'] = 200004;
                        $res_arr['tip'] = Settings::get('app_coin_name', '硬币').'抵扣不能超过'.$coin_pay_percent_every.'%';
                        return $res_arr;
                    }
                }
            }


            $balance = UserUtils::user_balance($uid);
            if($balance - $vip_price + $coin_blance < 0){
                $res_arr['code'] = 200012;
                return $res_arr;
            }

            $circle_info = WxCircle::where('id', $circle_id)->first();
            $paycontent_division = 0;
            $circle_user_id = 0;
            $circle_user_reward = 0;
            if($circle_info){
                $paycontent_division = $circle_info->circle_user_paycontent_division;
                $circle_user_id = $circle_info->user_id;
                $circle_user_reward = round($paycontent_division * $price, 2);
            }

            $platform_division = _between_(Settings::get('app_paypost_platform_percent', 0), 0, 100);
            $platform_reward = round($platform_division * $price / 100, 2);

            $orderModel = $this->createOrder($uid,4,'购买付费内容',$vip_price,$vip_price,$orderSn);

            if($coins_num > 0){
                $need_pay_price = $vip_price - $coin_blance;
                if($need_pay_price < 0.01){
                    // 金币支付
                    $pay_res2 = UserUtils::update_user_coins($uid,3, -$coins_num, '购买了付费内容(id: '.$post_id.')'.$vip_price_tip.'￥'.$vip_price.'（'. $coins_num.Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'.Settings::get('app_coin_name', '硬币').'-'.$coins_num);
                    if($pay_res2){
                        if($circle_user_reward >= 0.01 || $platform_reward >= 0.01){

                            UserUtils::update_user_financial($post_user_id, 12, ($price - $circle_user_reward - $platform_reward),
                                '<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>购买了您的付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)，获得余额￥'.($price - $circle_user_reward).'('.env('circle_user_call', '圈主').'获得￥'.$circle_user_reward.($platform_reward >= 0.01 ? '，平台获得￥'.$platform_reward : '').')');
                            if($circle_user_reward >= 0.01){
                                UserUtils::update_user_financial($circle_user_id, 14, $circle_user_reward, '圈子成员的付费内容被购买，订单金额￥'.$price.'，您获得分成￥'.$circle_user_reward.'(分成比例：'.($paycontent_division * 100).'%)');
                            }

                        }else{
                            UserUtils::update_user_financial($post_user_id, 12, $price, '<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>购买了您的付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)，获得余额+'.$price);
                        }

                        WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                        $user_pay = new WxUserPay();
                        $user_pay->user_id = $uid;
                        $user_pay->post_id = $post_id;
                        $user_pay->pay_content_id = $pay_content_id;
                        $user_pay->save();
                        WxCommentRepositores::add($post_id, 0, 0, $uid,  '💰'.$vip_price_tip.'购买了付费内容', '', 1);
                        // todo:
                        // 返回刷新内容
                        $data = WxPost::where('id', $post_id)->get();
                        $data = PostsRepositores::postsParame($data, $uid, $scene);

                        $res_arr['code'] = 1;
                        $res_arr['tip'] = '购买成功! 请手动刷新页面';
                        $res_arr['data'] = $data;
                        return $res_arr;
                    }else{
                        $res_arr['code'] = 200011;
                        return $res_arr;
                    }
                }else{
                    $r = UserUtils::update_user_financial($uid, 7, $need_pay_price, '(余额￥'.$need_pay_price.'+'. $coins_num .Settings::get('app_coin_name', '硬币').')'.$vip_price_tip.'购买付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)', $post_id);
                    if($r){
                        $pay_res2 = UserUtils::update_user_coins($uid,3, -$coins_num, '购买了付费内容(id: '.$post_id.')'.$vip_price_tip.'￥'.$vip_price.'（'. $coins_num.Settings::get('app_coin_name', '硬币').'抵扣了￥'.$coin_blance.'）：'.Settings::get('app_coin_name', '硬币').'-'.$coins_num);
                        if($pay_res2){
                            if($circle_user_reward >= 0.01){
                                UserUtils::update_user_financial($post_user_id, 12, ($price - $circle_user_reward),
                                    '<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>购买了您的付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)，获得余额￥'.($price - $circle_user_reward).'('.env('circle_user_call', '圈主').'获得￥'.$circle_user_reward.')');

                                UserUtils::update_user_financial($circle_user_id, 14, $circle_user_reward, '圈子成员的付费内容被购买，订单金额￥'.$price.'，您获得分成￥'.$circle_user_reward.'(分成比例：'.($paycontent_division * 100).'%)');
                            }else{
                                UserUtils::update_user_financial($post_user_id, 12, $price, '「<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>购买了您的付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">」'.$post_id.'</a>)，获得余额￥'.$price);
                            }
                            WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                            $user_pay = new WxUserPay();
                            $user_pay->user_id = $uid;
                            $user_pay->post_id = $post_id;
                            $user_pay->pay_content_id = $pay_content_id;
                            $user_pay->save();
                            WxCommentRepositores::add($post_id, 0, 0, $uid,  '💰'.$vip_price_tip.'购买了付费内容', '', 1);
                            // todo:
                            // 返回刷新内容
                            $data = WxPost::where('id', $post_id)->get();
                            $data = PostsRepositores::postsParame($data, $uid, $scene);

                            $res_arr['code'] = 1;
                            $res_arr['tip'] = '购买成功! 请手动刷新页面';
                            $res_arr['data'] = $data;
                            return $res_arr;
                        }else{
                            $res_arr['code'] = 200011;
                            return $res_arr;
                        }
                    }
                    $res_arr['code'] = 200037;
                    return $res_arr;
                }
            }else{
                $r = UserUtils::update_user_financial($uid, 7, $vip_price, '余额￥'.$vip_price.$vip_price_tip.'购买了付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)', $post_id);
                if($r){
                    if($circle_user_reward >= 0.01){
                        UserUtils::update_user_financial($post_user_id, 12, ($price - $circle_user_reward),
                            '「<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>」购买了您的付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)，获得余额￥'.($price - $circle_user_reward).'('.env('circle_user_call', '圈主').'获得￥'.$circle_user_reward.')');

                        UserUtils::update_user_financial($circle_user_id, 14, $circle_user_reward, '圈子成员的付费内容被购买，订单金额￥'.$price.'，您获得分成￥'.$circle_user_reward.'(分成比例：'.($paycontent_division * 100).'%)');
                    }else {
                        UserUtils::update_user_financial($post_user_id, 12, $price, '「<a href="/pages/user/user?id=' . $uid . '">' . $user_name . '</a>」购买了您的付费内容(id:<a href="/pages/sticky/sticky?id=' . $post_id . '">' . $post_id . '</a>)，获得余额￥' . $price);
                    }
                    WxOrder::where('order_number', $orderSn)->update(['order_state' => 1]);
                    $user_pay = new WxUserPay();
                    $user_pay->user_id = $uid;
                    $user_pay->post_id = $post_id;
                    $user_pay->pay_content_id = $pay_content_id;
                    $user_pay->save();
                    WxCommentRepositores::add($post_id, 0, 0, $uid,  '💰'.$vip_price_tip.'购买了付费内容', '', 1);
                    // todo:
                    // 返回刷新内容
                    $data = WxPost::where('id', $post_id)->get();
                    $data = PostsRepositores::postsParame($data, $uid, $scene);

                    $res_arr['code'] = 1;
                    $res_arr['tip'] = '购买成功! 请手动刷新页面';
                    $res_arr['data'] = $data;
                    return $res_arr;
                }
                $res_arr['code'] = 200037;
                return $res_arr;
            }
        }
    }


    /** app端公共查询订单状态函数
     * @param $query_state_no
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderAppCommonStatus(Request $request)
    {
        $query_state_no = _empty_default_($request->query_state_no, '');
        if(_empty_($query_state_no)){
            return $this->fail(200001, ['msg'=>'query_state_no为空']);
        }
        if(strpos($query_state_no, '_shoporder_') !== false){
            $order_id = Utils::outTradeNoPre($query_state_no, '');
            //1=未付款 2=已付款 3=已退款
            $shop_order = WxShopOrder::withTrashed()->where('order_id', $order_id)->first();
            if($shop_order){
                $tip = '支付失败';
                if(in_array($shop_order->pay_status, [2])){
                    $tip = '支付成功';
                }
                $status_tip = [0=>'正常', 1=>'未发货', 2=>'已发货', 3=>'确认收货', 4=>'已退货', 5=>'取消', 6=>'用户删除', 7=>'退款中', 8=>'自提发货待确定', 9=>'虚拟发货待确定'][$shop_order->status];
                if($shop_order->status == 8){
                    ShopOrderDeliverInfoManage::dispatch('query', $shop_order->id, null);
                }else if($shop_order->status == 10){
                    ShopOrderDeliverInfoManage::dispatch('virtual-query', $shop_order->id, null);
                }else if($shop_order->status == 9){
                    ShopOrderDeliverInfoManage::dispatch('virtual-upload', $shop_order->id, null);
                }
                return $this->success(['tip'=>$tip, 'order_type'=>'shop_order', 'pay_status'=>$shop_order->pay_status, 'status'=>$shop_order->status, 'msg'=>'ok',
                    'serial_number'=>$shop_order->serial_number, 'serial_platform'=>$shop_order->serial_platform,
                    'serial_platform_type'=>$shop_order->serial_platform_type, 'status_tip'=>$status_tip]);
            }else{
                return $this->fail(200003, ['msg'=>'查询不到order_id:'.$order_id.'的商品订单记录']);
            }
        }else if(strpos($query_state_no, '_order_') !== false){
            $order_number = Utils::outTradeNoPre($query_state_no, '');
            // (0未付款，1已付款，1已退款)
            $order = WxOrder::where('order_number', $order_number)->first();
            if($order){
                $tip = '支付失败';
                if(in_array($order->order_state, [1, 3, 4, 5, 6])){
                    $tip = '支付成功';
                }
                $status_tip = [0 => '未付款', 1 => '已付款', 2 => '已退款', 3=>'待小程序发货', 4=>'小程序发货中', 5=>'待小程序确定收货', 6=>'小程序确定收货中'][$order->order_state];
                if($order->order_state == 3){
                    OrderDeliverInfoManage::dispatch('upload', $order->id);
                }else if($order->order_state == 5){
                    OrderDeliverInfoManage::dispatch('query', $order->id);
                }
                // 注意：这里 $status + 1 目的是和商城订单的支付状态统一
                return $this->success(['tip'=>$tip, 'order_type'=>'order', 'pay_status'=>$order->order_state, 'order_state'=>$order->order_state, 'msg'=>'ok',
                    'serial_number'=>$order->order_serial_number, 'serial_platform'=>$order->order_serial_platform,
                    'serial_platform_type'=>$order->order_serial_platform_type, 'status_tip'=>$status_tip]);
            }else{
                return $this->fail(200003, ['msg'=>'查询不到order_number:'.$order_number.'的订单记录']);
            }
        }
        return $this->fail(200004, ['msg'=>'query_state_no不正确']);
    }

}
